简体   繁体   English

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

[英]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.

相关问题 为什么我需要在routerLink中添加“ /”,但在路由器定义中却没有“ /”? - Why I need to add '/' to routerLink but we do not have '/' in router definination? 使用赛普拉斯时,为什么需要显式清除sessionStorage? - Why do I need to explicitly clear sessionStorage when using Cypress? Angular2:如果服务已经包含在应用程序组件中,为什么必须在子组件中导入服务? - Angular2: Why do I have to import a Service in a child component if it is already included in the app component? 带笑话的角度:`verify()vs.expectOne()`? - Angular w/Jest: `verify()` vs.`expectOne()`? HttpTestingController ExpectOne仅验证api端点 - HttpTestingController expectOne verify only the api endpoint 如果该模式已经实现了这方面,是否需要? - Do I need required if the pattern already implement this aspect? 当我们拥有组件时,为什么需要服务? - Why do we need services when we have components? 为什么我需要标记检查? angular - Why do I need mark for check ? angular 为什么我需要订阅我的 Observable? - Why do I need to subscribe to my Observable? 为什么在 Angular 中实现 ControlValueAccessor 时需要在 writeValue 中调用 onChange 和 onTouch? - Why do I need call onChange and onTouch in writeValue when implementing ControlValueAccessor in Angular?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM