Monday, June 3, 2024
119
rated 0 times [  121] [ 2]  / answers: 1 / hits: 24852  / 4 Years ago, sun, november 15, 2020, 12:00:00

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?


More From » unit-testing

 Answers
59

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

[#50546] Saturday, October 31, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jensenb

Total Points: 634
Total Questions: 102
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Thu, Jun 24, 2021
3 Years ago
;