如何使用注入的服务测试 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
到控制器中,并监视 那个非常服务的函数em>.
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 is not a constructor (evaluating '$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
变量在 spyOn(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屋!