jefflau / jest-fetch-mock

Jest mock for fetch
MIT License
886 stars 117 forks source link

Typescript types do not include returned values, important object attributes #70

Closed EButlerIV closed 6 years ago

EButlerIV commented 6 years ago

mockResponse, mockResponseOnce, etc. do not return void

According to index.d.ts, mockResponse, etc all return void.

mockResponse(body: string, init?: MockParams): void;
mockResponseOnce(body: string, init?: MockParams): void;
mockResponses(responses: Array<{body: string, init?: MockParams}>): void;

In actuality, they all return the mocked fetch fn., so we can chain mockResponse calls.

fetch.mock isn't included in the definition

Since mock isn't included in the definition and the fetch definition doesn't extend jest's mocked function definition, uses of .mock.calls fail type checking.

jefflau commented 6 years ago

Would you have time to help write that definition? I am not a typescript developer but would welcome pull requests for it

EButlerIV commented 6 years ago

Sure. I'll submit a PR within the next few days.

jefflau commented 6 years ago

Thanks!

caseyduquettesc commented 6 years ago

For anyone looking for a temporary solution, they can alter the type globally, but in the test files, they'll need to refer to fetch using global.fetch instead. It's just a workaround for anyone being blocked.

// custom.jest.d.ts
import mockFetch from 'jest-fetch-mock';

declare global {
  namespace NodeJS {
    interface Global {
      fetch: JFM;
    }
  }
  type JFM1 = typeof mockFetch;
  export interface JFM extends JFM1, jest.MockInstance<any> {}
}
// setupJest.ts
import mockFetch from 'jest-fetch-mock';

global.fetch = (mockFetch as JFM);
// __tests__/demo.test.ts

it('works', () => {
  global.fetch.resetMocks();
  global.fetch.mockResponseOnce('');
  // fetch()
  expect(global.fetch.mock.calls.length).toEqual(1);
});
ravenscar commented 6 years ago

@EButlerIV looking at the docs for mockResponses I think the type signature is wrong. This isn't something you introduced I think it has always been wrong, I think it should be:

mockResponses(...responses : Array<[string] | [string, MockParams]>) : Fetch;

not

mockResponses(responses: Array<{body: string, init?: MockParams}>): Fetch;

What do you think?

billreed63 commented 6 years ago

This fix would be really helpful for me, do we have a ETA on when it will be merged? Thanks!

EButlerIV commented 6 years ago

Oh, sorry. I didn't see any of the subsequent conversation. @ravenscar is correct.