【问题标题】:Jest mocking: TypeError: axios.get.mockResolvedValue is not a function开玩笑:TypeError:axios.get.mockResolvedValue 不是函数
【发布时间】:2021-02-26 20:36:06
【问题描述】:

我有两个版本的相同代码,一个有效,一个抛出:

TypeError: axios.get.mockResolvedValue is not a function

作品:

const axios = require('axios')
jest.mock('axios') //<<<------

test('should mock axios', async () => {
  const resp = {data: {moreData: 'zedata'}}
  axios.get.mockResolvedValue(resp)
  const actualresp = await getAxios()
  expect(actualresp).toEqual({moreData: 'zedata'})
})

没有:

const axios = require('axios')

test('should mock axios', async () => {
  jest.mock('axios') //<<<------
  const resp = {data: {moreData: 'zedata'}}
  axios.get.mockResolvedValue(resp)
  const actualresp = await getAxios()
  expect(actualresp).toEqual({moreData: 'zedata'})
})

谁能帮我理解为什么在测试块内(或任何函数内)移动jest.mock('axios')会导致错误?

【问题讨论】:

标签: javascript unit-testing jestjs


【解决方案1】:

Jest 已在此链接 https://jestjs.io/docs/en/manual-mocks#mocking-node-modules 中明确说明了如何模拟模块。

它有一个重要的节点如下:

注意:为了正确地模拟,Jest 需要 jest.mock('moduleName') 与 require/import 语句在同一范围内。

另一方面,大多数用例jest.mock 应该在模块的顶层调用应该可以正常工作:

const axios = require('axios');
// At the same scope with `require`
jest.mock('axios');

【讨论】:

  • 谢谢我错过了这个。正在查看他们文档的不同部分。
猜你喜欢
  • 2020-02-24
  • 1970-01-01
  • 2021-06-25
  • 1970-01-01
  • 1970-01-01
  • 2020-08-24
  • 2021-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多