【发布时间】:2021-11-30 03:10:52
【问题描述】:
我的 Angular/Karma 测试存在覆盖率问题。
我创建了一个具有 signUp() 函数的组件
angularFireAuthSignOutSpyObj 是来自组件的 this.auth 的间谍(Firebase Auth)
signUp() {
if (this.registrationForm.valid) {
this.auth.createUserWithEmailAndPassword
(
this.registrationForm.get('email')?.value,
this.registrationForm.get('password')?.value
)
.then(() => {
this.appMessage = "Account created !";
})
.catch((error) => {
this.appMessage = error.message;
});
} else {
this.appMessage = 'Submit logic bypassed, form invalid !'
}
}
我正在使用业力测试来测试这个组件功能
it('should submit registration with form values', () => {
spyOn(component, 'signUp').and.callThrough();
angularFireAuthSignOutSpyObj.createUserWithEmailAndPassword.and.returnValue({
then: function () {
return {
catch: function () {
}
};
}
});
component.registrationForm.controls.email.setValue('test@email.com');
component.registrationForm.controls.password.setValue('ValidPass123');
component.registrationForm.controls.passwordCheck.setValue('ValidPass123');
expect(component.registrationForm.valid).toBeTruthy();
debugElement.query(By.css("button")).triggerEventHandler("click", null);
expect(component.signUp).toHaveBeenCalled();
expect(component.auth.createUserWithEmailAndPassword)
.toHaveBeenCalledWith(
component.registrationForm.controls.email.value,
component.registrationForm.controls.password.value)
// expect(component.appMessage).toEqual('Account created !');
});
你可以注意到最后一个 expect 被注释掉,因为它返回一个 Error: Expected undefined to equal 'Account created !'。 这是因为即使 this.auth.createUserWithEmailAndPassword 是在模拟服务 angularFireAuthSignOutSpyObj 中定义的,并且使用 2 个预期参数正确调用,我无法控制 then 和 catch 定义的函数。
它们的定义是为了在 signUp() 函数中尝试访问它时不会触发错误。但是我想做的是触发 then(() => ...) 和 catch(() => ...) 所以我可以测试/检查 app.message已正确更新。
所有异常都有效,直到最后一个。我觉得我需要修改我的 createUserWithEmailAndPassword.and.returnValue 中的某些内容,以可能返回触发 then 或 catch 的内容。
angularFireAuthSignOutSpyObj.createUserWithEmailAndPassword.and.returnValue({
then: function () {
return {
catch: function () {
}
};
}
});
有人知道如何测试我的组件的实际 auth.createUserWithEmailAndPassword 结果行为吗?
非常感谢!
大卫
【问题讨论】:
标签: angular typescript unit-testing testing karma-jasmine