【问题标题】:Trouble getting Jest mocks to work无法让 Jest 模拟工作
【发布时间】:2016-10-30 01:57:05
【问题描述】:

我在让 Jest 模拟工作时遇到了一些问题。

我正在尝试对具有一些由request 驱动的异步位的模块进行单元测试。

我目前的理解是:

  • 我可以使用jest.mock() 方法来模拟整个模块。
  • 我可以模拟 request.getrequest.post 等方法,以使它们同步并通过在 __mocks__/ 目录中创建文件来传递特定的响应。
  • Jest 将在需要/导入时自动模拟来自 __mocks__/ 的模块。
  • 我可以在将模块导入到测试文件中后加载 request 依赖项来覆盖它。

我认为我遗漏了一些明显的东西。

我要测试的模块:

// module.js
import request from 'request'

export default function foo() {
  let options = { /* ... */ }
  let callback = function (error, response, body) {
    if (!error && response.statusCode === 200) {
      return /* Response A */
    } else {
      return /* Response B */
    }
  }

  request.post(options, callback);
}

模拟请求模块:

// __mock__/request.js

function post(options, callback) {
  callback(undefined, {statusCode: 200})
}

const request = jest.genMockFromModule('request')
request.post = post

export default request;

模块测试:

// module.spec.js
import foo from './module'
jest.mock('request')

test('should return response A', function () {
  expect(foo()).toBe(/* Response A */)
});

当我运行模块测试时,

  • request 模块似乎没有被模拟,并且
  • foo 不会生成“响应 A”或“响应 B”

有人知道如何模拟这个来正确测试它吗?

【问题讨论】:

  • 因为您的函数foo 没有返回任何内容,因此测试将不起作用。你在测试期间是否在module.js 文件中记录了request,它真的不是模拟的吗,因为到目前为止设置看起来还不错。
  • 这是有道理的。这也可能会因为不从foo() 返回一个我可以在以后使用expect 的承诺而变得复杂,每个Jest's Async documentation。让我试一试并报告。

标签: javascript unit-testing mocking jestjs


【解决方案1】:

我猜,将 jest.mock('request') 移动到 import ... 之前会有所帮助。

【讨论】:

    猜你喜欢
    • 2021-11-06
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    相关资源
    最近更新 更多