我目前有这段代码...
const context = {};
context.response = {};
jest.mock('axios', () => ({
defaults: {
withCredentials: true
},
post: () => Promise.resolve(context.response)
}));
当我尝试运行时,我得到...
babel-plugin-jest-hoist: The module factory of
jest.mock()
is not allowed to reference any out-of-scope variables.
我希望能够轻松更改响应对象,而无需重置和重新模拟。有什么好的方法吗?
最佳答案
发生这种情况是因为开 Jest 使用 babel-plugin-jest-hoist ,这意味着什么,你所有的模拟都被提升到顶部。所以你不能访问模拟中的变量。
因为我们模拟了 axios,当我们导入“axios”时,我们得到了模拟版本,所以我们可以使用 jest.fn() 的“mockImplementation”方法。 .
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)
})
关于javascript - 如何在模拟的 Jest 函数中使用 var 作为返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56569791/