服务在配置阶段后由注入器 (inject(...)) 实例化。要测试您的初始化,您需要做的就是在每个测试中进行不同的设置。也就是说,与其在beforeEach 块中实例化您的服务,不如在测试中进行。
例如,您可以通过将internalService 模拟为具有param: true 来测试使用init1 实例化的副作用
describe('Unit: myService', function() {
it('should perform init1 if internalService.param', function() {
var mockInternalService = {
param: true,
};
// config phase (mocking)
module('app', function($provide) {
$provide.constant('internalService', mockInternalService);
});
inject(function($injector) {
myService = $injector.get('myService');
// assert side effects from init1();
});
});
});
要测试init2 的副作用,只需将internalService 模拟为param: false
it('should perform init2 if !internalService.param', function() {
var mockInternalService = {
param: false,
};
// config phase (mocking)
module('app', function($provide) {
$provide.constant('internalService', mockInternalService);
});
inject(function($injector) {
myService = $injector.get('myService');
// assert side effects from init2();
});
});
编辑:当然,如果您想对每个配置进行多次测试,您可以创建两个具有不同beforeEach 的describe 块。
describe('Unit: myService', function() {
var myService;
describe('When instantiated with `init1`', function() {
beforeEach(config(true));
beforeEach(inject(injections));
it('should do X');
});
describe('When instantiated with `init2`', function() {
beforeEach(config(false));
beforeEach(inject(injections));
it('should do Y');
});
function config(param) {
return function() {
var mockInternalService = {
param: param,
};
// config phase (mocking)
module('app', function($provide) {
$provide.constant('internalService', mockInternalService);
});
};
}
function injections($injector) {
myService = $injector.get('myService');
}
});