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

Time:09-22

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().

CodePudding user response:

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

i.e. 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();
  });

  • Related