Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 734
ilmoi Avatar asked Nov 15 '20 12:11

ilmoi


People also ask

Is it possible to mock Axios in jest?

Mocking Axios in Jest. Writing Tests involving Axios calls… | by Thinley Norbu | wesionaryTEAM | Medium Mock Axios calls using Jest & React Testing Library. Jest makes it easier to mock asynchronous requests.

What is the mock property in Python?

All mock functions have this special .mock property, which is where data about how the function has been called and what the function returned is kept. The .mock property also tracks the value of this for each call, so it is possible to inspect this as well:

How do I mock a module in jest?

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

How do you test a function with a mock?

To test this function, we can use a mock function, and inspect the mock's state to ensure the callback is invoked as expected. All mock functions have this special .mock property, which is where data about how the function has been called and what the function returned is kept.


1 Answers

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');
like image 100
tmhao2005 Avatar answered Oct 16 '22 19:10

tmhao2005