我试图用Jasmine编写自定义指令的测试用例。目前,我有一个设置如下所示的指令: 这是我在提琴手中的代码 http://jsfiddle.net/aHmPV/33/
app.directive('focusMe', function ($timeout) {
return {
scope: { trigger: '=focusMe' },
link: function (scope, element) {
scope.$watch('trigger', function (value) {
if (value === true) {
element[0].focus();
}
});
}
};
});
我的Jasmine代码在提琴手中 我试过不同的方法测试$ watch功能无法实现它,请帮忙
答案 0 :(得分:0)
您在scope.trigger
设置了$ watch,但会在focus-me
中传递。
您可以spyOn
使用element[0].focus
并为focus-me="true"
和focus-me="false"
创建测试:
describe('Directive: focusMe', function() {
var element,
scope;
beforeEach(module('CommonBusInfo'));
beforeEach(inject(function($rootScope) {
scope = $rootScope.$new();
}));
it("should focus if focus-me is true", inject(function($compile) {
element = angular.element('<input type="text" focus-me="true" value="chaitu">');
element = $compile(element)(scope);
spyOn(element[0], 'focus');
scope.$digest();
expect(element).toBeDefined();
expect(element[0].focus).toHaveBeenCalled();
}));
it("should NOT focus if focus-me is falsy", inject(function($compile) {
element = angular.element('<input type="text" focus-me="" value="chaitu">');
element = $compile(element)(scope);
spyOn(element[0], 'focus');
scope.$digest();
expect(element).toBeDefined();
expect(element[0].focus).not.toHaveBeenCalled();
}));
});