Mocking fetch: Jest test says response is wrong, but actually running the code works as expected

Viewed 648

I have an async event, createEvent, which contains fetch, meant to save data to a DB, and returns true on success and false on fail and null on error. It is actually doing so properly, as demonstrated by running this code:

let result = await createEvent(newEvent);
console.log("Result:", result);
if (result) {
  setMessage("Event added!");
} else {
  setMessage("Error adding event, please try again later");
}

In this case, the console logs true and the message is set correctly.

However, when I run the following test, it fails:

global.fetch = jest.fn(() => 
    Promise.resolve({
        json: () => Promise.resolve({ success: true }),
    })
);

it('returns proper value', () => {
    expect(createEvent(newEvent)).toBe(true);
});

This is the relevant output from Jest:

console.log src/components/EventForm.js:60
    Fetch response: { json: [Function: json] }

  console.log src/components/EventForm.js:66
    resJson: { success: true }
.
.
.
expect(received).toBe(expected) // Object.is equality

    Expected: true
    Received: {}

I'm not sure why Jest would be getting different results. I'm new to Jest and testing in general, so open to any other corrections as well. Any help is appreciated, thank you!

1 Answers

You just need to mark your test async and await the execution of the createEvent() call before your expectation:

it('returns proper value', async () => {
  const result = await createEvent(newEvent);
  expect(result.success).toBe(true);
});

Edit goofy-hamilton-mho0q (go to Tests tab on the right)

Alternately, if you don't want to deal with the manual mocking of fetch, you can checkout jest-fetch-mock.

Related