Angular指令单元测试:$ templateCache或$ httpBackend?

时间:2016-01-14 14:22:37

标签: angularjs unit-testing jasmine angular-directive

我正在测试使用templateUrl属性的指令,并且想知道编译模板的最佳方法是什么。使用$templateCache$httpBackend会更好吗?我猜测使用$templateCache会更好,因为我认为这是它的用例,但我已经看到它做到了两种方式。虽然我还没有让$httpBackend方法完全正常运行。

注意:第二个测试用于重写原始项目。第一个测试来自原始项目。

$templateCache方式:

describe('buttonToggle', function() {
    var elm, scope;

    beforeEach(module('app'));
    beforeEach(module('src/app/partials/buttonToggle/buttonToggle.html'));

    beforeEach(inject(function($templateCache, _$compile_, _$rootScope_) {
        template = $templateCache.get('src/app/partials/buttonToggle/buttonToggle.html');
        $templateCache.put('src/app/partials/buttonToggle/buttonToggle.html', template);

        $compile = _$compile_;
        $rootScope = _$rootScope_;
    }));

    it('should have an on/off switch', function() {
        var buttonElement = angular.element('<button-toggle></button-toggle>');
        var element = $compile(buttonElement)($rootScope);
        $rootScope.$digest();

        expect(element.text()).toContain('ON');
        expect(element.text()).toContain('OFF');
    });
});

$httpBackend的非工作实现:

describe('The buttonToggle directive', function() {

    var $compile,
        $scope,
        $httpBackend,
        btElement,
        btElementPath = 'client/modules/buttonToggle/buttonToggle.html',
        btElementFileName = 'buttonToggle.html';

    beforeEach(module('app'));

    beforeEach(inject(function(_$compile_, _$rootScope_, _$httpBackend_) {
        $compile = _$compile_;
        $scope = _$rootScope_;
        $httpBackend = _$httpBackend_;
        $httpBackend.whenGET(btElementPath).respond(200);
        $httpBackend.expectGET(btElementFileName).respond(200);
        btElement = $compile('<button-toggle></button-toggle>')($scope);
        $scope.$digest();
    }));

    it('should be defined', function() {
        expect(btElement.html()).toContain('btn');
    });
});

此外,关于如何让后一种测试工作的任何想法?我不认为我正确设置了whenGET,因为我从断言中得到的错误表明编译的元素是空的。

1 个答案:

答案 0 :(得分:0)

我实际上从Angular文档中找到了一个简短的答案。如果其他人对这个问题有很好的了解,那么请随时回答,但这就是我发现的:

  

如果您的指令使用templateUrl,请考虑使用karma-ng-html2js-preprocessor预编译HTML模板,从而避免在测试执行期间通过HTTP加载它们。否则,如果测试目录层次结构与应用程序不同,则可能会遇到问题。

相关问题