简体   繁体   中英

Why do I need verify() when I already have expectOne()?

I am learning Angular unit testing from some online courses.

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:

Verify that no unmatched requests are outstanding.

I was wondering why I need to call verify() when I already called expectOne().

httpTestingController.verify(); is useful for cases when you want to verify that specific HTTP requests were not sent.

ie when there is conditional logic around an HTTP request.

// 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();
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM