javascriptapiunit-testingjestjsfetch-mock

fetch-mock: No fallback response defined for POST


All my GET requests are going through but POST ones fail. This happens when I update fetch-mock from 7.3.0 to 7.3.1 or later.

console.warn Unmatched POST to url

Error fetch-mock: No fallback response defined for POST to url

http.js

export const get = (url) => {
  const options = {
    method: 'GET',
    credentials: 'same-origin'
  };

  return fetch(url, options).then(handleJsonResponse);
};

export const post = (url, body) => {
  const headers = {
    'content-type': 'application/json',
    'pragma': 'no-cache',
    'cache-control': 'no-cache'
  };

  return fetch(url, {
    credentials: 'same-origin',
    method: 'POST',
    cache: 'no-cache',
    body: JSON.stringify(body),
    headers
  }).then(handleJsonResponse);
};

http.spec.js

const url = '/path/to/url'

describe('get', () => {
    it('makes a GET request', async () => {
      fetchMock.mock({
        name: 'route',
        matcher: url,
        method: 'GET',
        credentials: 'same-origin',
        response: {
          status: 200,
          body: []
        }
      });

      const response = await get(url);

      expect(fetchMock.called()).toEqual(true);
      expect(fetchMock.calls().length).toEqual(1);
      expect(fetchMock.calls('route').length).toEqual(1);
      expect(response).toEqual([]);
    });
  });

  describe('post', () => {
    const requestBody = {request: 'request'};

    it('makes a POST request', async () => {
      fetchMock.mock({
        name: 'route',
        matcher: url,
        method: 'POST',
        credentials: 'same-origin',
        cache: 'no-cache',
        body: JSON.stringify(requestBody),
        headers: {
          'content-type': 'application/json',
          'pragma': 'no-cache',
          'cache-control': 'no-cache'
        },
        response: {
          status: 200,
          body: []
        }
      });

      const response = await post(url, requestBody);

      expect(fetchMock.called()).toEqual(true);
      expect(fetchMock.calls().length).toEqual(1);
      expect(fetchMock.calls('route').length).toEqual(1);
      expect(fetchMock.lastOptions().headers).toEqual({
        'content-type': 'application/json',
        'pragma': 'no-cache',
        'cache-control': 'no-cache'
      });
      expect(response).toEqual([]);
    });
  });

Any thoughts on what's causing this? Is there a way to get more meaningful logs to help with debugging this?

I would rather not go the alternative path of trying nock or jest-fetch-mock.


Solution

  • Alright, after hours of digging into the library itself I have found out where the issue was.

    In my code (and the snippet above) I am stringifying the body JSON.stringify(body). The library's generate-matcher.js is parsing it JSON.parse(body) and then compares the two - the point which was causing the failure. I am now just sending it as the raw object.