[英]Why do I need verify() when I already have expectOne()?
I am learning Angular unit testing from some online courses.我正在从一些在线课程中学习 Angular 单元测试。
Here is a part of the code.这是代码的一部分。
it("should find a course by id", () => {
coursesService.findCourseById(12).subscribe((course) => {
expect(course).toBeTruthy();
expect(course.id).toBe(12);
});
const req = httpTestingController.expectOne("/api/courses/12");
expect(req.request.method).toEqual("GET");
req.flush(COURSES[12]);
httpTestingController.verify();
});
The definition of verify() on the angular document is: angular文档上verify()的定义是:
Verify that no unmatched requests are outstanding.
验证没有未完成的不匹配请求。
I was wondering why I need to call verify() when I already called expectOne().我想知道为什么我已经调用了expectOne() 时还需要调用verify()。
httpTestingController.verify();
is useful for cases when you want to verify that specific HTTP requests were not sent.当您想要验证特定的 HTTP 请求是否未发送时,这很有用。
ie when there is conditional logic around an HTTP request.即,当围绕 HTTP 请求存在条件逻辑时。
// component.ts
ngOnInit(): void {
this.http.get('my-api-request').subscribe(...);
if (this.id != undefined) {
this.http.get('my-additional-request').subscribe(...);
}
}
// component.spec.ts
it("should only do one request when id does not exist", () => {
this.component.id = 1;
this.fixture.detectChanges();
const req = httpTestingController.expectOne("my-api-request");
expect(req.request.method).toEqual("GET");
req.flush({});
// will fail since `id` is defined. Without this verify the test will pass.
httpTestingController.verify();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.