简体   繁体   中英

How to mock with strict TypeScript

For example:

let mockhttp; // 1

beforeEach(() => {
    mockhttp = { //3
        get: jest.fn()
    };

    mockhttp.get.mockReturnValue(of(...)); //4
});

it('should fetch', async () => {
    const service = new MyService(mockhttp as any as HttpClient); //2
});

This will give the following error on 1 and 2.

Variable 'mockhttp' implicitly has type 'any' in some locations where its type cannot be determined.

Changing let mockhttp; to let mockhttp: HttpClient;

Gives on 3:

Type '{ get: Mock ; }' is missing the following properties from type 'HttpClient': handler, request, delete, head, and 5 more.

and on 4:

TS2339: Property 'mockReturnValue' does not exist on type '{ (url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCred...'

Is there a way to solve this without adding //@ts-ignore everywhere?

Note: this question is not about testing the httpclient or anything related. It is just for demo purpose. It could be any other service or component.

Angular provides a nice package for testing HTTP communication.

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;
  let httpMock: HttpTestingController;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      declarations: [AppComponent]
    })
      .compileComponents();

    httpMock = TestBed.inject(HttpTestingController);
  }));

Here is a nice article with examples: Testing Angular HTTP Communication .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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