嘲讽整个模块时,你得到的实际功能
我曾经嘲笑使用jest.genMockFromModule('winston');
从哪里我需要winston
,如果我console.log(winston)
嘲笑的功能也即将至此第三方库。但是,它应该只进来只是测试用例文件。
我在做什么错在这里?
__mocks__
winston.js
const winston = jest.genMockFromModule('winston');
logger.js
const winston = require('winston')
console.log(winston) // object consist of mockFunctions
回答如下:
无论我需要
winston
,如果我console.log(winston)
嘲笑的功能也即将
您可以通过创建Manual mock for a Node module,这意味着__mocks__/winston.js
“将自动嘲笑”创造了一个winston
。
需要注意的是mocking a Node module行为与mocking a user module或嘲讽核心Node
模块,因为该模块自动嘲笑,并呼吁jest.mock
不要求不同。
换句话说,因为__mocks__/winston.js
存在,即模拟将自动从require('winston')
任意代码运行的过程中你的测试返回。
我曾经嘲笑使用
jest.genMockFromModule('winston');
第三方库
调用jest.genMockFromModule
在这种情况下是不必要的,因为winston
自动嘲笑。
事实上,呼吁jest.genMockFromModule
结束了使用“自动嘲讽系统产生嘲笑版”,要求winston
,这最终成为您在__mocks__/winston.js
模拟返回的模块。
换句话说,在这种情况下jest.genMockFromModule('winston');
最终回到你的手册模拟的自动模拟。
我在做什么错在这里?
在__mocks__/winston.js
模拟将由require('winston')
返回。
要需要测试使用jest.requireActual
在实际模块:
const winstonMock = require('winston'); // this will return the mock
const winston = jest.requireActual('winston'); // this will return the actual module
笔记:
jest.requireActual
版本21.0.0加入jest.requireActual
并直到它被固定PR 7404这是在版本发布24.0.0没有正确的节点模块工作