I currently have this code...
const context = {};
context.response = {};
jest.mock('axios', () => ({
defaults: {
withCredentials: true
},
post: () => Promise.resolve(context.response)
}));
When I try to run I get...
babel-plugin-jest-hoist: The module factory of
jest.mock()
is not allowed to reference any out-of-scope variables.
I want to be able to easily change the response object without resetting and remocking. Is there a good way to do this?
That happens because of jest use babel-plugin-jest-hoist , what it means, all of your mocks hoisted to the top. so you can't access variables inside mocks.
Because we mocked axios, when we import 'axios' we get the mock version so we can use "mockImplementation" method of jest.fn() .
import axios from 'axios'
jest.mock('axios', () => ({
defaults: {
withCredentials: true
},
post: jest.fn()
}))
test('should...', () => {
// mock post for your case
axios.post.mockImplementation(() => {
return true
})
expect(axios.post()).toBe(true)
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.