鉴于此指令:
angular.module(moduleName).
directive("dir1", function() {
return {
restrict: "AE",
scope: {
myvar: '='
},
templateUrl: "app/directives/dir1.html",
link: function (scope, element, attrs) {
scope.myvar = "Hello";
}
}
});
使用此模板dir1.html
:
<span class="myclass">{{myvar}}</span>
我试图用以下方式进行单元测试:
fdescribe("dir1 Directive", function() {
var scope,element;
beforeEach(module(moduleName));
beforeEach(module('app/directives/dir1.html'));
beforeEach(inject(function ($templateCache,$rootScope,$compile) {
var formElement = angular.element('<div dir1></div>');
scope = $rootScope.$new();
element = $compile(formElement)(scope);
scope.$digest();
}));
it("should have content", function() {
expect(element.find('class')).toEqual('myclass');
expect(element.find('span').text).toEqual('Hello');
})
});
在测试中我试图检索class属性的值和span元素中文本的内容,但我得到:
Expected ({ length: 0, prevObject: ({ 0: HTMLNode, length: 1 }),
context: undefined, selector: 'class' }) to equal 'myclass'.
test/directives/dir1.test.js:20:40
loaded@http://localhost:9876/context.js:151:17
Expected Function to equal 'Hello'.
test/directives/dir1.test.js:21:44
loaded@http://localhost:9876/context.js:151:17
我做错了什么?
答案 0 :(得分:0)
对于那些感兴趣的人,这是解决方案(感谢JB Nizet)
it("should have content", function() {
var span = element.find('span');
expect(span.hasClass('myclass')).toEqual(true);
expect(span.text()).toEqual('Hello');
})