【问题标题】:How do I use a var as the return value in a mocked Jest function?如何在模拟的 Jest 函数中使用 var 作为返回值?
【发布时间】:2019-10-27 09:59:02
【问题描述】:

我目前有这个代码...

const context = {};
context.response = {};
jest.mock('axios', () => ({
    defaults: {
        withCredentials: true
    },
    post: () => Promise.resolve(context.response)
}));

当我尝试跑步时,我得到...

babel-plugin-jest-hoist:jest.mock() 的模块工厂不允许引用任何超出范围的变量。

我希望能够轻松更改响应对象,而无需重置和移除。有什么好办法吗?

【问题讨论】:

    标签: javascript jestjs jest-mock-axios


    【解决方案1】:

    这是因为开玩笑使用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)
    })
    

    【讨论】:

    • 我实际上是在看到你的帖子之前想出的:-)。这里的答案相同
    猜你喜欢
    • 1970-01-01
    • 2020-08-04
    • 2022-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    相关资源
    最近更新 更多