I have a few tests that needs a service. I am using a stub service named UserServiceStub
that I inject in my SettingsComponent
, which I am testing. I reset the UserServiceStub in each test, but, tests are executed asynchronous so when I reset my UserServiceStub (which is an injectable and singleton class) other test has already initialized it. My tests are weak and asserts are wrong :-(
I would like to do synchronous test or a different UserServiceStub instance for each test, but I don't know how to do it...
I tried to define a method in UserServiceStub called reset()
that resets stub service, but because it's asynchronous it doesn't work. Also, I executed in afterEach()
method, the TestBed.resetTestEnvironment()
method but it does not work either.
My reset()
method:
reset() {
this.user = { IBAN: '', SWIFT: '', paypal: '', app_idioma: '' };
}
user
and it has being overwritten by other tests My beforeEach()
method is this one
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;
});
A test:
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('');
}))
);
I hope your answers, if you got any question just ask.
Thanks :-)
Did you try using getter/setter? This way value of UserServiceStub.user
won't be modified (if I understood correctly what you want).
class UserServiceStub {
// instead of:
// this.user = { IBAN: '', SWIFT: '', paypal: '', app_idioma: '' };
// use:
get user() { return { IBAN: '', SWIFT: '', paypal: '', app_idioma: '' }; }
set user(value) { /* test something here */ }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.