-1

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.

Robin Dijkhof
  • 18,665
  • 11
  • 65
  • 116

1 Answers1

-1

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.

IAfanasov
  • 4,775
  • 3
  • 27
  • 42