【问题标题】:How would I mock the axios call in my controller in express?我将如何在我的控制器中以 express 模拟 axios 调用?
【发布时间】:2021-08-15 22:24:29
【问题描述】:

所以我的 axios 调用是一个已经分离的模块,并通过模拟 axios 本身进行了测试。但是,当我将此功能导入控制器时,测试控制器本身的最佳方法是什么?我知道它需要被模拟,但我不确定最有效的模拟方式,因此我可以测试 req 和 res(它们也被模拟)。

axios 调用是getAddressWithPostcode

控制器

const findAddress = async (req: Request<Params>, res: Response, next: NextFunction) => {
  const { params } = req

  await getAddressWithPostcode(params)
    .then((data) => {
      if (!isUndefined(data.status)) {
        return res.status(data.status).send(data.data.Message)
      }

      return res.send(data)
    })
    .catch(err => {
      next(err)
    })
}

Axios 调用:

const getAddressWithPostcode = async (params: Params) => {
  const { postCode, number } = params

  const addressUrl = `${process.env.URL}/${postCode}${number
    ? `/${number}?api-key=${process.env.API_KEY}`
    : `?api-key=${process.env.API_KEY}`}`

  try {

    const { data } = await axios.get(addressUrl)
    return data

  } catch (e) {

    const { response } = e
    return response

  }
}

【问题讨论】:

    标签: javascript node.js typescript express jestjs


    【解决方案1】:
        // users.test.js
    import axios from 'axios';
    import Users from './users';
    
    jest.mock('axios');
    
    test('should fetch users', () => {
      const users = [{name: 'Bob'}];
      const resp = {data: users};
      axios.get.mockResolvedValue(resp);
    
      // or you could use the following depending on your use case:
      // axios.get.mockImplementation(() => Promise.resolve(resp))
    
      return Users.all().then(data => expect(data).toEqual(users));
    });
    

    这个例子使用 jest 来测试一个 axios 调用,同样可以扩展到任何库。希望它能让你开始

    可以通过开玩笑 here找到更多关于单元测试的细节

    【讨论】:

    • 我理解需要mock解析的值,我想做的是测试控制器中resp对象的状态和数据,以及axios调用
    • 如果你已经模拟了 axios,只需编写一个单元测试,执行 axios.post('yourendpoint').then((res)=>{ expect(res).tobe(your mockresponse) }) 相当简单
    猜你喜欢
    • 2021-09-21
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 2022-12-03
    • 2019-08-02
    • 2020-08-09
    • 2015-06-10
    • 1970-01-01
    相关资源
    最近更新 更多