在我的评论之后,下面是如何测试表单是否正确提交。
假设您有一个接口
Patient
:
export interface Patient {
id: number;
name: string;
}
在组件中,您有一个表单,可以通过
submit()
:
submit() {
this.patientService.savePatient(this.patient).subscribe(result => {
console.log('Patient created');
});
}
现在,您的服务进行HTTP调用并检查字段是否正常:
savePatient(patient: Patient): Observable<any> {
if (typeof patient.id !== number) { return Observable.throw('ID is not a number'); }
if (typeof patient.name !== string) { return Observable.throw('Name is not a string'); }
return this.http.post<any>(this.url, patient);
}
那么你的测试应该是这样的。首先,组件:
it('Should call the service to save the patient in DB', () => {
// Spy on service call
// Expect spy to have been called
});
it('Should log a message on success', () => {
// Spy on console log
// Expect console log to have been called with a string
});
您还可以测试错误处理是否正确,是否有错误代码等。
现已投入使用:
it('Should throw an error if the ID is not a number', () => {
// Mock a patient with a string ID
// Expect an error to be thrown
});
// Same thing for the name, you get the idea
it('Should make an HTTP call with a valid patient', () => {
// Spy on the HttpTestingController
// Expect the correct endpoint to have been called, with the patient as the payload
});
这些测试的总体思路是
涵盖任何可能发生的情况
。这将允许您防止
副作用
:例如,如果有一天您决定将ID传递给字符串,那么单元测试将失败并告诉您
你希望我发送一个字符串,但我只传递一个数字
这是单元测试的目的。