Jasmine spec 没有期望(有的时候)

Jasmine spec has no expectations (when there are)

我知道有一些类似的问题,但找不到可以解决我的问题的问题。

所以我有以下测试(有 6 个期望):

  it('should redirect to error page when there is a 403 error', fakeAsync(() => {
    const mockError403Response: HttpErrorResponse = new HttpErrorResponse({
      error: '403 error',
      status: 403,
      statusText: 'Forbidden'
    });

    httpClient.get("/v1/test").subscribe(_ => { },
      (error: HttpErrorResponse) => {
        expect(error).toBeTruthy();
        expect(routerSpy.navigate).toHaveBeenCalled();
        expect(routerSpy.navigate).toHaveBeenCalledWith(['/error', 403]);
        expect(error.status).toEqual(mockError403Response.status);
        expect(error.error).toContain(mockError403Response.error);
        expect(error.statusText).toContain(mockError403Response.statusText);
      });

    let request: TestRequest;
    request = httpTestingController.expectOne("/v1/test");
    request.flush(mockError403Response);
    tick(500);
  }));

然后我收到警告:

Spec 'should redirect to error page when there is a 403 error' has no expectations.

关于如何解决这个问题有什么建议吗?

我在想,它永远不会进入您订阅的错误块中。

您必须为 flush 中的错误响应传递第二个对象。现在,您的测试将进入订阅块的 _ => { }

试试这个:

 it('should redirect to error page when there is a 403 error', fakeAsync(() => {
    const mockError403Response: HttpErrorResponse = new HttpErrorResponse({
      error: '403 error',
      status: 403,
      statusText: 'Forbidden'
    });

    httpClient.get("/v1/test").subscribe(_ => { 
       // Call Jasmine fail to ensure if it comes here, the test is a failure.
       // Before your test was traversing here.
       fail(); 
    },
      (error: HttpErrorResponse) => {
        // ensure you see this log.
        console.log('!! Making assertions !!');
        expect(error).toBeTruthy();
        expect(routerSpy.navigate).toHaveBeenCalled();
        expect(routerSpy.navigate).toHaveBeenCalledWith(['/error', 403]);
        expect(error.status).toEqual(mockError403Response.status);
        expect(error.error).toContain(mockError403Response.error);
        expect(error.statusText).toContain(mockError403Response.statusText);
      });

    let request: TestRequest;
    request = httpTestingController.expectOne("/v1/test");
    // modify this line
    request.flush(mockError403Response, { status: 403, statusText: 'Forbidden' });
    tick(500);
  }));

检查 了解如何模拟 Http 错误。