【问题标题】:How to test an async function with callback in Jest?如何在 Jest 中使用回调测试异步函数?
【发布时间】:2020-10-09 07:25:12
【问题描述】:

我很难找到有关如何测试此功能的信息:

const MyService = {
  async stringify (entry, cb) {
    try {
      const response = await axios.post('localhost:3005/stringify', {
        entry
      })
      
      cb(null, response.data)

    } catch (minificationError) {

      if (minificationError.response.status === 500) {
        cb('error 1', null)
      } else {
        cb('error 2', null)
      }

    }
  }
}

我知道我可以像这样导入axios 并模拟.post

axios.post.mockResolvedValue({
   data: { some: 'value' }
})

如果我的 MyService 正在返回承诺,那就太好了……但是我该如何处理回调呢?这是一种不好的做法吗?服务应该返回承诺,然后处理组件函数中的错误吗?

此外,我将如何用 jest 模拟状态代码(以测试失败的状态?)

【问题讨论】:

  • 这是一种不好的做法,服务应该返回承诺,然后处理组件函数中的错误吗? - 肯定。

标签: javascript reactjs unit-testing jestjs enzyme


【解决方案1】:

首先,您必须设置模拟 axios,然后您必须在测试用例中调用模拟 API

const axios = {
  post: jest.fn(() => {
    return Promise.resolve({
      data: {},
    });
  }),

  create: () => axios,
  request: {},
  defaults: {
    adapter: {},
    headers: {},
  },
  interceptors: {
    request: {
      use() {},
    },
    response: {
      use() {},
    },
  },
};

一旦您设置了模拟 axios,您就可以在您的测试用例中访问并返回您想要的任何模拟响应和状态代码。

mockAxios.post.mockImplementation((url) => {
  if (url.includes("something")) {
    return Promise.resolve({ data:{"response":""}, status: 200 });
  } 
  return Promise.reject(new Error("not found"));
});

【讨论】:

  • 谢谢。定义 axios 与使用 jest.mock("axios") 有何不同?
猜你喜欢
  • 1970-01-01
  • 2022-11-10
  • 1970-01-01
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多