【问题标题】:How to test axios requests in jest如何开玩笑地测试 axios 请求
【发布时间】:2020-06-24 12:13:03
【问题描述】:

我想开玩笑地测试 axios 请求。 问题是我已经搜索了很多方法,但没有理解其中的一堆,我被困住了。 例如这里是我获取请求

  componentDidMount() {
const { getAll, setPageCount } = this.props.actions;
axios
  .get(`http://localhost:8080/${localStorage.getItem("username")}`, {
    headers: {
      "auth-token": localStorage.getItem("auth-token"),
    },
  })
  .then((res) => {
    getAll(res.data);
    setPageCount();
  })
  .catch((err) => {
    console.log("-----token", localStorage.getItem("auth-token"));
    console.log("err", err);
  });
  }

我怎样才能开玩笑呢? 提前致谢

【问题讨论】:

  • 对于 Jest 测试,您是否希望 API 实际调用;向端点发送请求还是简单地模拟 axios API?
  • 模拟 axios API。
  • 你看过Mock Modules吗?

标签: javascript reactjs jestjs axios


【解决方案1】:

使用spyOn 模拟一个承诺。 最终完成的示例:

test('Test', async () => {
    const props = {
      actions: {
        getAll: jest.fn(),
        setPageCount: jest.fn()
      }
    };
    const wrapper = shallow(<YourComponent {...props} />);
    const getSpySuccess = jest.spyOn(axios, 'get').mockImplementation(() => {
      return new Promise((resolve, reject) => {
        return resolve({
          data:{}
        });
      });
    });
    
    wrapper.instance().componentDidMount();
    
    await wrapper.update();
    
    expect(getSpySuccess).toHaveBeenCalledTimes(1);
    expect(props.actions.getAll).toHaveBeenCalledTimes(1);
    expect(props.actions.setPageCount).toHaveBeenCalledTimes(1);
    expect(getSpySuccess).toBeCalledWith(
      `http://localhost:8080/${localStorage.getItem("username")}`
    );
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-20
    • 2020-08-16
    • 1970-01-01
    • 2018-08-05
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    相关资源
    最近更新 更多