Я кодирую тест на Angular.
Компонент, который я хочу протестировать, имеет следующий код:
ngOnInit() {
this.cognitoService.isAuthenticated().then(() => this.loadForm(),
() => this.router.navigate(['/home/login']));
}
loadForm() {
this.createFormControls();
this.createForm();
this.userProperties = new Map();
this.cognitoService.getUserAttributes(['name', 'custom:lastName', 'email', 'picture', 'phone_number',
'custom:id', 'custom:description']).subscribe(attributes => this.completeProfileForm(attributes));
}
cognitoService.isAuthenticated () Метод возвращает обещание.И метод cognitoService.getUserAttributes возвращает Observable.
Тест выглядит следующим образом:
it('should create', () => {
spyOn(cognitoService, 'getUserAttributes').and.callFake(function () {
const userProperties = new Map();
userProperties.set('custom:lastName', 'lastName');
userProperties.set('name', 'firstName');
userProperties.set('email', 'example@email.com');
userProperties.set('picture', 'picture.png');
userProperties.set('phone_number', '+5412123434');
userProperties.set('custom:id', '1');
userProperties.set('custom:description', 'description');
return Observable.of(userProperties);
});
spyOn(cognitoService, 'isAuthenticated').and.returnValue(Promise.resolve());
component.ngOnInit();
fixture.detectChanges();
expect(component).toBeTruthy();
fixture.whenStable().then(() => {
expect(component).toBeTruthy();
});
});
Таким образом, когда я запускаю тест, терминал показывает: Пустой набор тестов Но если я изменю код следующим образом:
ngOnInit() {
this.cognitoService.isAuthenticated().then(null,
() => this.router.navigate(['/home/login']));
this.loadForm();
}
Тест выполняется нормально.Но мне не нравится этот код раньше, потому что я хочу вызывать метод loadForm () только тогда, когда обещание выполнено.
Знаете ли вы, что происходит?