如何使用注入服务测试Angular 1.6组件? [英] How to test Angular 1.6 component with injected service?
问题描述
我想测试我的Angular组件,该组件基于 John Papa的样式指南:
I want to test my Angular component which is syntactically based on John Papa's styleguide:
'use strict';
angular.module('MyModule')
.component('MyCmpnt', MyCmpnt())
.controller('MyCtrl', MyCtrl);
function MyCmpnt() {
return {
restrict: 'E',
templateUrl: 'myPath/myTemplate.html',
bindings: {
foo: '=',
bar: '<'
},
controller: 'MyCtrl',
controllerAs: 'vm'
};
}
MyCtrl.$inject = ['MyService'];
function MyCtrl (MyService) {
// controller logic
}
如您所见,我想注入 MyService
到控制器中,并 spy 在该服务上的函数中.
As you can see I want to inject MyService
into the controller and spy in a function on that very service.
我的测试代码:
'use strict';
describe('component: MyCmpnt', function () {
var $componentController,
MyService;
beforeEach(module('MyModule'));
beforeEach(module(function ($provide) {
$provide.value('MyService', MyService);
spyOn(MyService, 'serviceFunc').and.callThrough();
}));
beforeEach(inject(function (_$componentController_) {
$componentController = _$componentController_;
}));
it('should initiate the component and define bindings', function () {
var bindings = {
foo: 'baz',
bar: []
};
var ctrl = $componentController('MyCmpnt', null, bindings);
expect(ctrl.foo).toBeDefined();
});
});
但是,此设置使我遇到以下错误:
However, this setup lets me run into the following error:
TypeError:undefined不是构造函数(评估'$ componentController('MyModule',null,bindings)')
TypeError: undefined is not a constructor (evaluating '$componentController('MyModule', null, bindings)')
推荐答案
上面的代码具有$componentController('MyModule'...
,并且没有MyModule
组件.
The code above has $componentController('MyModule'...
, and there is no MyModule
component.
MyService
变量.这将引发错误,导致应用程序无法正确引导.
MyService
variable is undefined when spyOn(MyService...
is called. This will throw an error prevent the application from being bootstrapped correctly.
如果测试平台使用PhantomJS,则可能会导致beforeEach
块中的错误抑制,建议使用正确的错误报告Chrome Karma启动器.
If testing rig uses PhantomJS, this may lead to error suppression in beforeEach
blocks, for correct error reporting Chrome Karma launcher is recommended.
如果问题是在定义模拟服务时未定义MyService
,则可以将其作为存根就地定义:
If the problem is that MyService
is undefined at the point where mocked service is defined, it can be defined in-place as a stub:
beforeEach(module(function ($provide) {
$provide.value('MyService', {
serviceFunc: jasmine.createSpy().and.callThrough()
});
}));
这篇关于如何使用注入服务测试Angular 1.6组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!