[英]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: 我目前的理解是:
jest.mock()
method to mock the entire module. jest.mock()
方法来模拟整个模块。 request.get
, request.post
, etc to make them synchronous and pass particular responses by creating a file inside a __mocks__/
dir. request.get
, request.post
等,以使其同步并通过在__mocks__/
目录内创建文件来传递特定的响应。 __mocks__/
when they're required/imported. __mocks__/
模拟模块。 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, 当我运行模块测试时,
request
module does not appear to be mocked, and request
模块似乎没有被嘲笑,并且 Anyone know how to mock this to test it properly? 任何人都知道如何模拟它以正确测试吗?
我猜想,在import ...
之前移动jest.mock('request')
可以帮助您的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.