【发布时间】:2019-03-08 17:12:53
【问题描述】:
我有一个需要将配置对象传递给服务的 Angular 服务:
// my.module.ts
@NgModule({ ... })
export class MyModule {
static forRoot(config: MyServiceConfig): ModuleWithProviders {
return {
ngModule: MyModule,
providers: [{ provide: MyServiceConfig, useValue: config }],
};
}
}
//my.service.ts
export class MyService {
constructor(private _http: HttpClient, @Optional() config: MyServiceConfig) {
if (config) {
if (!config.attr1) {
throw new Error('You must provide the attr1 to use this Module.');
} else if (!config.attr2) {
throw new Error('You must provide the attr2 to use this Module.');
} else {
this.attr1 = config.attr1;
this.attr2 = config.attr2;
}
} else {
throw new Error(
'You must provide a MyServiceConfig object with the attr1 and the attr2 to use this module.',
);
}
}
}
这一切都有效,但我想围绕向服务提供该配置对象编写几个测试。我在测试文件中有以下beforeEach,当未提供配置对象时它按预期抛出错误:
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [FeedbackService],
});
});
但是当我试图将它从beforeEach 移到单独的测试中时,我无法正确抛出错误。如果它完全按照上面的方式调用,但在测试中,它会:
it('should do something', () => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [FeedbackService],
});
});
我在try/catch 块中尝试了上述操作,试图捕捉错误,但它给了我一个误报。我尝试了expect(() => {}).toThrowError() 和toThrow() 方法,但即使将TestBed.configureTestingModule() 放在expect 中的箭头函数内也不起作用。这样做不会引发错误。
有没有办法做到这一点?另外,有没有办法向服务提供配置对象以测试它是否将服务属性设置为正确的值?
【问题讨论】:
标签: angular unit-testing testing jasmine