我需要测试一个包含 $element 的指令 Controller 。所以我有一个像这样的函数:
function func($event) {
$element.find('#la-la-la').focus();
}
并在测试中渲染它:
template = $compile(element)($scope);
$scope.$apply();
controller = element.controller('myDirective');
我要做的是在该指令的 Controller 中测试这个函数。
describe('func method', function testFunc() {
it('should focus on element', function checkFocusing() {
controller.func();
expect(focusSpy).toHaveBeenCalled();
});
});
其中“focusSpy”是模拟 $element 服务中的 spy 。 但似乎如果我使用 $provide.service('$element', ...) 测试找不到它。在编译之前将其注入(inject) $scope.$element 也不起作用。谢谢!
最佳答案
好的,我找到了一个可能的解决方案。您不能模拟 $element,因为它是指令 Controller 的私有(private)变量,但由于它是一个 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 - 在 Jasmine 中 mock Angular $元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38102643/