开玩笑的嘲笑:TypeError:axios.get.mockResolvedValue不是一个函数

问题描述 投票:0回答:3

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

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
3个回答
39
投票

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');

4
投票

对我来说,解决方案是显式声明

axios.get
一个模拟函数:

axios.get = jest.fn();

这为

mockResolvedValue
添加了
axios.get
和其他功能。


0
投票

对我来说,以下作品

jest.mock('axios');
const mockedAxios = axios as jest.MockedFunction<typeof axios>;
© www.soinside.com 2019 - 2024. All rights reserved.