我的单元测试有问题需要在能够测试之前设置指令。
这是我初始化它的方式:
var elm, $templateCache
var count = 0;
beforeEach(module('app/js/directives/templates/mytemplate.html'));
beforeEach(inject(function($injector) {
$templateCache = $injector.get('$templateCache');
}));
beforeEach(inject(
['$httpBackend','$compile','$rootScope', function(_$compile) {
var template = $templateCache.get('app/js/directives/templates/mytemplate.html');
if(count == 0 ){
$httpBackend.expectGET('js/directives/templates/mytemplate.html').respond(template);
}
elm = angular.element('<div my-directive</div>');
$compile(elm)($rootScope);
if(count == 0){
$httpBackend.expectGET('/app/js/content/some.json').respond('{ "left" : "<div>Contact information</div>"}');
$httpBackend.flush();
}
$rootScope.$digest();
count++;
}]
));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it("should work like I want it to", function() {
$rootScope.my-directive.somefunction();
expect($rootScope.somevalue).toBe(2);
});
it("should load the previous page if the function scope.layover.qa_pager.prev is called", function() {
$rootScope.my-directive.someotherfunction();
expect($rootScope.somevalue).toBe(1);
});
这样可行,但在我看来,不应该需要计算黑客。如果我把它遗漏了,我会遇到$ httpbackend的问题,它似乎每次都没有重新初始化,所以它给了我'错误:不满意的请求:GET /app/js/content/some.json'和'错误:没有待定要求冲洗!'
答案 0 :(得分:0)
对我而言,您似乎正在尝试为单元测试加载模板。我假设你正在使用业力来运行测试,所以你应该看看html2js。它会将模板加载到模板缓存中。
https://github.com/karma-runner/karma-ng-html2js-preprocessor
// karma.conf.js
module.exports = function(config) {
config.set({
preprocessors: {
'**/*.html': ['ng-html2js']
},
files: [
'*.js',
'*.html'
],
ngHtml2JsPreprocessor: {
// strip this from the file path
stripPrefix: 'public/',
// prepend this to the
prependPrefix: 'served/',
// or define a custom transform function
cacheIdFromPath: function(filepath) {
return cacheId;
}
}
});
};