javascript - 如何在模拟的 Jest 函数中使用 var 作为返回值?

标签 javascript jestjs jest-mock-axios

我目前有这段代码...

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/

相关文章:

angular - "Expected to be running in ' ProxyZone ', but it was not found."开 Jest

jestjs - 避免有条件地调用 `expect` : jest testing error

javascript - JS Jest Mocking - 预期收到未定义的错误

javascript - react 中的 Mapbox(ReferenceError : L is not defined)

javascript - jQuery 表单提交与 document.form.submit

Javascript 的 super 构造函数 - 澄清吗?

node.js - ReactJs Jest :`jsdom 4. x 及以上版本仅适用于 io.js,不适用于 Node.jsT:

javascript - React 子组件在 componentWillUnmount 之后丢失其父组件的引用

带有 @HostLinener 的 Angular Jest 测试指令 ('window:scroll' )