繁体   English   中英

为什么我已经有了 expectOne() 还需要 verify()?

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

我正在从一些在线课程中学习 Angular 单元测试。

这是代码的一部分。

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

  });

angular文档上verify()的定义是:

验证没有未完成的不匹配请求。

我想知道为什么我已经调用了expectOne() 时还需要调用verify()。

httpTestingController.verify(); 当您想要验证特定的 HTTP 请求是否未发送时,这很有用。

即,当围绕 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.

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