[英]Basic Karma Angular 1.5 Component Test
我不确定自己在做什么是完全错误的,但是当我从“指令”切换到“组件”以定义一些HTML元素时,突然间我破坏了所有的Karma测试。 这是我所拥有的:
karam.conf.js
...
preprocessors: {
'module-a/module-a.view.html': ['ng-html2js'],
...,
'module-z/module-z.view.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
moduleName: 'theTemplates'
},
...
module-a.component.js
(function(){
"use strict";
angular.module('ModuleA').component('moduleAComponent',{
controller: 'ModuleAController as moduleAVm',
templateUrl: 'module-a/module-a.view.html'
});
})();
module-a-tests.js
"use strict";
describe('ModuleA',function(){
beforeEach(module('ModuleA'));
describe('Controller',function(){
...
});
describe('Component',function(){
var element, $rootScope;
beforeEach(module('theTemplates'));
beforeEach(inject([
'$compile','$rootScope',
function($c,$rs) {
$rootScope = $rs;
element = $c('<module-a-component></module-a-component>')($rootScope);
$rootScope.$digest(); // ???
}
]));
it('should have moduleAVm',function(){
expect(element.html()).not.toBe(''); // FAILS HERE
expect(element.html()).toContain('moduleVm'); // FAILS HERE TOO
});
});
});
错误:
Expected '' not to be ''.
好的,在更详尽地阅读了Angular的文档之后,我遇到了以下语句:
对组件控制器进行单元测试的最简单方法是使用ngMock中包含的$ componentController。 此方法的优点是您不必创建任何DOM元素。 以下示例从上方显示了如何对heroDetail组件执行此操作。
它突然出现在我身上,我的describe('Controller',function(){...}); 这是我真正需要更改的内容,我应该摆脱“组件”部分(正式称为“指令”)
现在是我的“控制器”:
beforeEach(inject([
'$componentController', // replaced $controller with $componentController
function($ctrl){
ctrl = $ctrl('queryResults',{ // Use component name, instead of controller name
SomeFactory:MockSomeFactory,
SomeService:MockSomeService
});
}
]));
现在,我仍然要测试我的控制器,同时测试组件。 而且,我不再需要使用$ compile,$ rootScope等创建DOM元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.