如何模拟箭头函数中的提取调用?

时间:2020-04-23 21:14:21

标签: reactjs testing fetch

我正在尝试测试删除在React中数据库中保存的特定数据的函数的调用。问题是我只想模拟fetch调用并使其他所有程序照常运行,因为现在无论何时运行测试,数据都会在数据库中删除。

这是我的删除功能代码:

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");
  };

这是我的测试代码:

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();
});

我得到了被称为:0的期望值(global.fetch).toHaveBeenCalledTimes(1); 和为Expect(historyMock.push.mock.calls [0])。toEqual([“ / eventList”])定义的Received:未定义;

任何帮助都会很棒

1 个答案:

答案 0 :(得分:0)

尝试使用以下方法代替使用spyOn(global, fetch)

global.fetch = jest.fn().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();
});