javascript – 在jasmine中模拟angular $元素
作者:互联网
我需要在里面用$element测试一个指令控制器.所以我有一个像这样的功能:
function func($event) {
$element.find('#la-la-la').focus();
}
并在测试中呈现它:
template = $compile(element)($scope);
$scope.$apply();
controller = element.controller('myDirective');
而我正在尝试做的是在该控制器内为该指令测试此函数.
describe('func method', function testFunc() {
it('should focus on element', function checkFocusing() {
controller.func();
expect(focusSpy).toHaveBeenCalled();
});
});
其中“focusSpy”是一个内部模拟$元素服务的间谍.
但似乎如果我使用$provide.service(‘$element’,…),测试找不到它.在编译之前将它注入$scope.$元素也不起作用.谢谢!
解决方法:
好吧,我找到了一个可能的解决方案.你不能模拟$元素,因为它是指令控制器的私有变量,但由于它是一个jQuery元素,你可以监视jQuery本身:
describe('func method', function testFunc() {
it('should focus on element', function checkFocusing() {
spyOn($.fn, 'find').and.callThrough();
spyOn($.fn, 'focus').and.callThrough();
controller.func();
expect($.fn.find).toHaveBeenCalledWith('#la-la-la');
expect($.fn.focus).toHaveBeenCalled();
});
});
标签:javascript,angularjs,unit-testing,jasmine,karma-jasmine 来源: https://codeday.me/bug/20190702/1353802.html