ilmoi
ilmoi

Reputation: 2534

Jest mocking: TypeError: axios.get.mockResolvedValue is not a function

I have 2 versions of the same code, one works, one throws:

TypeError: axios.get.mockResolvedValue is not a function

Works:

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

Doesn't:

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

Can someone help me understand why moving jest.mock('axios') inside the testblock (or inside any function, for that matter) results in an error?

Upvotes: 38

Views: 47515

Answers (3)

JX Hu
JX Hu

Reputation: 11

For me, the following works

jest.mock('axios');
const mockedAxios = axios as jest.MockedFunction<typeof axios>;

Upvotes: 0

bergie3000
bergie3000

Reputation: 1131

For me the solution was to explicitly declare axios.get a mock function:

axios.get = jest.fn();

This adds mockResolvedValue and other functions to axios.get.

Upvotes: 4

tmhao2005
tmhao2005

Reputation: 17504

Jest has clearly addressed how to mock a module in this link https://jestjs.io/docs/en/manual-mocks#mocking-node-modules.

It has an important note as following:

Note: In order to mock properly, Jest needs jest.mock('moduleName') to be in the same scope as the require/import statement.

On the other hand, Most of use cases jest.mock is supposed to be called at the top level of module should work properly:

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

Upvotes: 43

Related Questions