小编典典

使用templateUrl进行单元测试AngularJS指令

angularjs

我有一个已templateUrl定义的AngularJS指令。我正在尝试与Jasmine进行单元测试。

根据此建议,我的JasmineJavaScript如下所示:

describe('module: my.module', function () {
    beforeEach(module('my.module'));

    describe('my-directive directive', function () {
        var scope, $compile;
        beforeEach(inject(function (_$rootScope_, _$compile_, $injector) {
            scope = _$rootScope_;
            $compile = _$compile_;
            $httpBackend = $injector.get('$httpBackend');
            $httpBackend.whenGET('path/to/template.html').passThrough();
        }));

        describe('test', function () {
            var element;
            beforeEach(function () {
                element = $compile(
                    '<my-directive></my-directive>')(scope);
                angular.element(document.body).append(element);
            });

            afterEach(function () {
                element.remove();
            });

            it('test', function () {
                expect(element.html()).toBe('asdf');
            });

        });
    });
});

当我在Jasmine spec错误中运行此命令时,出现以下错误:

TypeError: Object #<Object> has no method 'passThrough'

我想要的只是让templateUrl原样加载-
我不想使用respond。我相信这可能与使用ngMock而不是ngMockE2E有关。如果是罪魁祸首,如何使用后者而不是前者?

提前致谢!


阅读 240

收藏
2020-07-04

共1个答案

小编典典

我最终要做的是获取模板缓存并将视图放入其中。我没有控制不使用ngMock,事实证明:

beforeEach(inject(function(_$rootScope_, _$compile_, $templateCache) {
    $scope = _$rootScope_;
    $compile = _$compile_;
    $templateCache.put('path/to/template.html', '<div>Here goes the template</div>');
}));
2020-07-04