我有一个Submit方法,该方法调用一个方法,然后在名为 errorMessage 的字符串消息中更新状态。提交方法类似于:
onSubmit() {
this.userProfileForm = new UserForm(this.firstName.value, this.lastName.value, this.email.value, null, this.phone.value,
this.description.value, this.profileImage.value);
this.updateUserAttributes().then(() => {
this.userService.updateUser(this.id, new UserModel(this.firstName.value,
this.lastName.value, this.email.value, this.phone.value, this.description.value, null)).subscribe(
() => this.errorMessage = 'Success');
console.log(this.errorMessage);
},
() => {
console.log('Error');
this.errorMessage = 'Error';
}
);
}
如您所见,该方法中有日志。 我正在编写测试以验证Submit方法的方法,但无法正常工作。
测试如下:
spyOn(cognitoService, 'updateUserAttributes').and.returnValue(Promise.resolve(true));
spyOn(userService, 'updateUser').and.returnValue(Observable.of(new UserModel(component.firstName.value,
component.lastName.value, component.email.value, component.phone.value, component.description.value, null)));
const firstNameControl = component.profileForm.controls['firstName'];
firstNameControl.setValue('newFirstName');
firstNameControl.markAsTouched();
fixture.detectChanges();
component.onSubmit();
fixture.detectChanges();
console.log('component.errorMessage: ' + component.errorMessage);
expect(firstNameControl.valid).toBeTruthy();
expect(component.errorMessage).toBe('Success');
在测试中,我还将打印 errorMessage 属性。 在控制台中,日志以这种方式显示:
'component.errorMessage: undefined'
'Success'
Expected undefined to be 'Success'.
第一个日志是测试的日志,然后是方法的日志。情况应该相反。 方法updateUserAttributes()返回一个Promise,它在Submit方法中处理,但似乎在测试中不起作用。
您知道如何进行测试以等待Submit事件的结束以验证属性errorMessage吗?
谢谢!
答案 0 :(得分:0)
我在测试中使用 whenStable 方法解决了该问题。
现在测试看起来像这样:
it('when submit with correct result, it should ok and show an ok message', () => {
spyOn(cognitoService, 'updateUserAttributes').and.returnValue(Promise.resolve(true));
spyOn(userService, 'updateUser').and.returnValue(Observable.of(new UserModel(component.firstName.value,
component.lastName.value, component.email.value, component.phone.value, component.description.value, null)));
const firstNameControl = component.profileForm.controls['firstName'];
firstNameControl.setValue('newFirstName');
firstNameControl.markAsTouched();
fixture.detectChanges();
component.onSubmit();
fixture.detectChanges();
console.log('component.errorMessage: ' + component.errorMessage);
fixture.whenStable().then(() => {
expect(firstNameControl.valid).toBeTruthy();
expect(component.errorMessage).toBe('Success');
});
});