現在、ディレクティブのテスト (Jasmine を使用) を書いていますが、リンク機能がトリガーされていないと思われます。
ディレクティブは次のとおりです。
.directive('userWrapperUsername', [
'stringEntryGenerateTemplate',
'stringEntryGenerateLinkFn',
// UserWrapper username column
// Attribute: 'user-wrapper-username'
// Attribute argument: A UserWrapper object with a 'newData' key into an
// object, which contains a 'username' key holding the
// UserWrapper's username
function(stringEntryGenerateTemplate, stringEntryGenerateLinkFn) {
return {
template: stringEntryGenerateTemplate('username'),
restrict: 'A',
scope: true,
link: stringEntryGenerateLinkFn('userWrapperUsername', 'username')
};
}
])
そのため、ファクトリを通じて提供される 2 つの関数、つまりstringEntryGenerateTemplate
とを利用しstringEntryGenerateLinkFn
ます。
このstringEntryGenerateTemplate
関数は文字列を受け取り、文字列を返します。
このstringEntryGenerateLinkFn
関数は、呼び出されると、実際のリンク関数を返します。これは主にイベント ハンドラーで構成されているため、次のように簡略化します。
function stringEntryGenerateLinkFn(directiveName, key) {
return function(scope, element, attr) {
scope.state = {};
scope.userWrapper = scope.$eval(attr[directiveName]);
}
}
ディレクティブの使用方法は次のとおりです。
<div user-wrapper-username="u"></div>
これが私のテストケースです:
describe('UserWrapper Table string entry', function() {
var $scope
, $compile;
beforeEach(inject(function($rootScope, _$compile_) {
$scope = $rootScope.$new();
$compile = _$compile_;
}));
it('should be in stateDisplay if the value is non empty', function() {
var userWrapper = {
orgData: {
student: {
hasKey: true,
value: 'abcdef'
}
},
newData: {
student: {
hasKey: true,
value: 'abcdef',
changed: false
}
}
}
, key = 'student'
, elem
, elemScope;
$scope.userWrapper = userWrapper;
elem = $compile('<div user-wrapper-username="userWrapper"></div>')($scope);
elemScope = elem.scope();
expect(elemScope.userWrapper).toBe(userWrapper);
expect(elemScope.state).toEqual(jasmine.any(Object)); // this fails
});
});
elemScope.state
そのため、未定義であるというテスト失敗が発生します。scope.state = {};
リンク関数が実行された場合に実行する必要があるステートメントがあったことを思い出してください。リンク機能の内部を試しましたconsole.log
が、同様に実行されません。
では、リンク機能をトリガーするにはどうすればよいですか?
ありがとう!