javascript - 在 Jasmine 中 mock Angular $元素

标签 javascript angularjs unit-testing jasmine karma-jasmine

我需要测试一个包含 $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/

相关文章:

javascript - 如何在页面上运行输入js

javascript - jQuery 在某个 div 开始页面而不滚动

javascript - 如何在 ui-router angularjs 中仅更改子 ui-view,同时保持父级相同?

javascript - 允许空值-输入类型数字(angularjs)

javascript - 即使在 false 上,Cordova 相机也会保存到画廊

javascript - 如何初始化 Angular 默认路由?

javascript - 如何将整个背景逆向移动到鼠标指针的光标 p5.js

java - appengine 单元测试仅获取 10 个实体

unit-testing - 测试驱动开发的缺点?

c - 从一个简单的 c 单元测试开始