如何在模拟的 Jest 函数中使用 var 作为 return 值?

How do I use a var as the return value in a mocked Jest function?

我目前有这个代码...

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.

我希望能够轻松更改响应对象,而无需重新设置和重新模拟。有什么好的方法吗?

发生这种情况是因为玩笑使用 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)
})