繁体   English   中英

Jasmine 规范没有期望(有时)

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

关于如何解决这个问题的任何建议?

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

您必须通过第二个 object 才能在flush中获得错误响应。 现在,您的测试将 go 放入订阅块的_ => { }中。

尝试这个:

 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 错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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