jefflau / jest-fetch-mock

Jest mock for fetch
MIT License
882 stars 116 forks source link

[Questions] - Testing the catch #170

Closed JamesSingleton closed 3 years ago

JamesSingleton commented 3 years ago

So I have something that looks like the following:

fetch(url)
      .then((response) => {
        // If the Content-Type is not text/html throw an error
        const contentType = response.headers.get('content-type');
        if (!contentType.includes('text/html')) {
          throw new Error('Content-Type was not of type text/html');
        }
        // Read the response as text.
        return response.text();
      })
      .then((data) => sendResponse(res, data))
      .catch(() => sendError(res, errorResponse));

I am able to test the .then((data) => sendResponse(res, data)) just fine with

fetch.mockResponse((input) => {
        expect(input).toHaveProperty('url', url);
        return Promise.resolve(response);
      }, {
        headers: {
          'content-type': 'text/html',
        },
      });

return fetch(url).then((resp) => {
        expect(resp.headers.get('content-type')).toEqual(responseInit.headers['content-type']);
        return expect(resp.text()).resolves.toEqual(response);
      });

However, there aren't really any examples on how to test .catch with jest-fetch-mock. I tried doing

fetch.mockResponse('', {
        headers: {
          'content-type': 'text/plain',
        },
      });

and

return fetch(url).then((resp) => {
        expect(resp.headers.get('content-type')).toEqual(responseInit.headers['content-type']);
        return expect(resp).rejects.toThrow('Content-Type was not of type text/html');
      });

But now luck.

JamesSingleton commented 3 years ago

Decided to go another wrote for mocking.