简体   繁体   English

使Jest模拟游戏无法正常工作

[英]Trouble getting Jest mocks to work

I'm having some trouble getting Jest mocking to work. 我在使Jest模拟工作上遇到麻烦。

I'm trying to unit-test a module that has some asynchronous bits in driven by request . 我正在尝试对具有由request驱动的异步位的模块进行单元测试。

My understanding is currently that: 我目前的理解是:

  • I can use the jest.mock() method to mock the entire module. 我可以使用jest.mock()方法来模拟整个模块。
  • I can mock the methods request.get , request.post , etc to make them synchronous and pass particular responses by creating a file inside a __mocks__/ dir. 我可以模拟方法request.getrequest.post等,以使其同步并通过在__mocks__/目录内创建文件来传递特定的响应。
  • Jest will automock modules from the __mocks__/ when they're required/imported. 当需要/导入时,Jest将自动从__mocks__/模拟模块。
  • I can override the request dependency by loading it after I import the module that imports it into the test file. 在导入将request导入测试文件的模块后,可以通过加载request依赖项来覆盖它。

I think I'm missing something obvious. 我想我缺少明显的东西。

Module I want to test: 我要测试的模块:

// 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);
}

Mocked request module: 模拟请求模块:

// __mock__/request.js

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

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

export default request;

Module test: 模块测试:

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

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

When I run the module tests, 当我运行模块测试时,

  • the request module does not appear to be mocked, and request模块似乎没有被嘲笑,并且
  • foo does not generate either "Response A" or "Response B" foo不会生成“响应A”或“响应B”

Anyone know how to mock this to test it properly? 任何人都知道如何模拟它以正确测试吗?

我猜想,在import ...之前移动jest.mock('request')可以帮助您的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM