lquixada / cross-fetch

Universal WHATWG Fetch API for Node, Browsers and React Native.
MIT License
1.67k stars 104 forks source link

Help mocking cross-fetch with Jest #131

Closed ellier closed 2 years ago

ellier commented 2 years ago

Hi, Can you provide an example on how to mock cross-fetch?

I'm getting the following error when I try to mock it with Jest: TypeError: crossFetch.mockResolvedValue is not a function.

This is what I tried:

`const http = require('cross-fetch');

jest.mock('cross-fetch', () => { //Mock the default export return { __esModule: true, default: jest.fn() }; });

test('should do a mock fetch', () => { http.mockResolvedValue({ status: 200, json: () => {{ user: testUser }}, }); expect(http().status).toEqual(200); });`

Any help will be appreciated. Thanks.

ellier commented 2 years ago

As easy as:

`const http = require('cross-fetch'); jest.mock('cross-fetch');

http.mockImplementation( () => Promise.resolve( { json: () => ({ error: 'Error' }), status: () => 401, text: () => { "error": "Error" } } )); `