1

I took the exact code sample from jest-fetch-mock npm package example and I cannot make it fail. Can anyone tell me what am I doing wrong?

This is my code:

require('jest-fetch-mock').enableMocks();

const APIRequest = (who) => {
  if (who === 'google') {
    return fetch('https://google.com').then((res) => res.json());
  } else {
    return 'no argument provided';
  }
};

describe('testing api', () => {
  beforeEach(() => {
    fetch.resetMocks();
  });

  it('calls google and returns data to me', () => {
    fetch.mockResponseOnce(JSON.stringify({ data: '12345' }));

    //assert on the response
    APIRequest('google').then((res) => {
      expect(res.data).toEqual('not 12345');
    });
  });
});

Even if, clearly, my mock response for the fetch doesn't match my expected result, jest still says the test passed , why? It tells me above the "test passed" section that it received something else than what was expected, but the test still shows "passed", why ? How can I make it fail in this situation, how it is actually expected in this situation.

Dominik
  • 6,078
  • 8
  • 37
  • 61
Bogos Robert
  • 193
  • 2
  • 9
  • 1
    Don't forget that inside a promise like `.then(() => { blah blah })`, that that code executes asynchronously. – xdhmoore Apr 15 '21 at 07:28
  • 1
    Your test finishes before the `.then()` is executed. Make your callback function you pass to `it()` `async` and then `await` `APIRequest('google')`. (So `let res = await APIRequest('google'); expect(res.data).toEqual('not 12345');`) – Ivar Apr 15 '21 at 07:30

1 Answers1

3

There are 2 possible solutions to your issue:

  1. Use the expect.assertions to make jest verify whether all assertions have been asserted and return a promise:
  it('calls google and returns data to me', () => {
    fetch.mockResponseOnce(JSON.stringify({ data: '12345' }));

    expect.assertions(1);

    //assert on the response
    return APIRequest('google').then((res) => {
      expect(res.data).toEqual('not 12345');
    });
  });
});

If you return a Promise, jest will know that the code runs async.

  1. Use async/await

Make use of the async/await syntax:

it('calls google and returns data to me', async () => {
    fetch.mockResponseOnce(JSON.stringify({ data: '12345' }));

    expect.assertions(1);

    //assert on the response
    const result = await APIRequest('google')
    expect(result).toEqual('not 12345');
  });
});
Titulum
  • 9,928
  • 11
  • 41
  • 79