【发布时间】:2016-04-19 22:00:05
【问题描述】:
我正在测试使用 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');
});
});
我对@987654328@ 的非工作实现:
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,因为我从断言中得到的错误表明编译的元素为空。
【问题讨论】:
-
你搞定了吗?我也有同样的问题。Thnx。
标签: angularjs unit-testing jasmine angular-directive