使用 templateUrl 对 AngularJS 指令进行单元测试 [英] Unit Testing AngularJS directive with templateUrl

查看:27
本文介绍了使用 templateUrl 对 AngularJS 指令进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 AngularJS.

Using AngularJS.

有一个指令.

指令定义了templateUrl.

指令需要单元测试.

目前正在使用 Jasmine 进行单元测试.

Currently unit testing with Jasmine.

推荐如下代码:

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 中运行代码.

Running code in Jasmine.

获取错误:

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

templateUrl 需要按原样加载

templateUrl needs loading as-is

不能使用respond

可能与 ngMock 的使用有关而不是 ngMockE2E 使用.

May be related to ngMock use rather than ngMockE2E use.

推荐答案

我最终做的是获取模板缓存并将视图放在那里.我无法控制不使用 ngMock,事实证明:

What I ended up doing was getting the template cache and putting the view in there. I don't have control over not using ngMock, it turns out:

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

这篇关于使用 templateUrl 对 AngularJS 指令进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆