我有一些需要服务的测试。我正在使用一个名为UserServiceStub
的存根服务,将其注入到我正在测试的SettingsComponent
中。我在每个测试中重置UserServiceStub
,但是由于测试是异步执行的,所以当我重置我的UserServiceStub
时(它是一个可注入和单例类),其他测试已经初始化了它。我的测试很薄弱,断言也是错误的 :-(
我想要进行同步测试或为每个测试使用不同的UserServiceStub
实例,但我不知道怎么做...
我尝试在UserServiceStub
中定义一个名为reset()
的方法来重置存根服务,但由于它是异步的,所以它不起作用。此外,我在afterEach()
方法中执行了TestBed.resetTestEnvironment()
方法,但它也不起作用。
我的reset()
方法:
reset() {
this.user = { IBAN: '', SWIFT: '', paypal: '', app_idioma: '' };
}
- 我正在使用的属性名为
user
,但它已被其他测试覆盖
我的beforeEach()
方法如下:
let fixture: ComponentFixture<SettingsComponent>;
let settingsComponent: SettingsComponent;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [SettingsComponent],
imports: [],
providers: [
TranslateService,
AppService,
{ provide: MockBackend, useClass: MockBackend },
{ provide: HttpToolsService, useValue: HttpToolsServiceStub },
{ provide: BaseRequestOptions, useClass: BaseRequestOptions },
{ provide: UserService, useClass: UserServiceStub } // My stub UserService
]
});
fixture = TestBed.createComponent(SettingsComponent);
settingsComponent = fixture.componentInstance;
});
一项测试:
it('#updateSettings should doesn\'t update the user\'s settings when is wrong', fakeAsync(
inject([UserService, HttpToolsService, MockBackend],
(userService: UserServiceStub, httpToolsService: HttpToolsService, mockBackend: MockBackend) => {
userService.reset(); // It does not work...
userService.isError = true;
// However, I have reseted my user in UserServiceStub,
// this returns false because settingsComponent.getSettings().IBAN is actually 'XXX'
// instead of '' (empty) how it has to be
expect(settingsComponent.getSettings().IBAN).toBe('');
}))
);
我希望您能提供答案,如果您有任何问题,请随时问。谢谢 :-)