jeudi 23 avril 2020

How to mock a fetch call that is within an arrow function?

I'm trying to test the invocation of a function that deletes specific data saved in a database in React. The problem is I want to only mock the fetch call and have everything else run as usual because right now whenever tests are run the data gets deleted in the database.

Here is my code for the delete function:

deleteEvent = async () => {
    try {
      await fetch(
        "api url",
        {
          method: "DELETE",
        }
      )
        .then((res) => res.json())
        .then(
          (result) => {
            console.log(result);
          },
          (error) => {
            console.log(error);
          }
        );
    } catch (error) {
      console.error(error);
    }
    this.props.history.push("/eventList");
  };

And here is my test code:

test("deleteEvent function works", (done) => {
  const mockSuccessResponse = {};
  const mockJsonPromise = Promise.resolve(mockSuccessResponse);
  const mockFetchPromise = Promise.resolve({
    json: () => mockJsonPromise,
  });
  jest.spyOn(global, "fetch").mockImplementation(() => mockFetchPromise);

  const historyMock = { push: jest.fn() };
  const wrapper = shallow(<EventState history={historyMock} />);
  wrapper.instance().deleteEvent();
  expect(global.fetch).toHaveBeenCalledTimes(1);
  expect(historyMock.push.mock.calls[0]).toEqual(["/eventList"]);
  global.fetch.mockClear();
  done();
});

I get number times called: 0 for the expect(global.fetch).toHaveBeenCalledTimes(1); and a Received: undefined for the expect(historyMock.push.mock.calls[0]).toEqual(["/eventList"]);

Any help would be great

Aucun commentaire:

Enregistrer un commentaire