【问题标题】:mocking angular $element in jasmine在茉莉花中模拟角度$元素
【发布时间】:2016-11-01 08:11:27
【问题描述】:

我需要测试一个带有 $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”是模拟 $element 服务中的间谍。 但似乎如果我使用 $provide.service('$element', ...) 它不会被测试发现。在编译之前将其注入 $scope.$element 也不起作用。谢谢!

【问题讨论】:

    标签: javascript angularjs unit-testing jasmine karma-jasmine


    【解决方案1】:

    好的,我找到了可能的解决方案。你不能模拟 $element 因为它是指令控制器的私有变量,但由于它是一个 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();
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-14
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多