【问题标题】:get the actual function when mocking the entire module模拟整个模块时获取实际功能
【发布时间】:2019-02-03 13:09:35
【问题描述】:

我使用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.js 文件怎么样?你能分享剩下的吗?

标签: javascript node.js jestjs


【解决方案1】:

无论我需要winston,如果我console.log(winston),模拟函数也将出现

您通过创建__mocks__/winston.js 创建了Manual mock for a Node module,这意味着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 的 mock 将由 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 在 Node 模块中无法正常工作,直到它被 PR 7404 修复,它在版本 24.0.0 中发布

【讨论】:

  • 我已经尝试了 jest.requireActual 但仍然抛出错误
  • 我已经发布了整个代码,在这里stackoverflow.com/questions/54502290/…,你能告诉我我在这里做错了什么
  • 即使制作 jest.requireActualModel 并制作一个 console.log(winston) 它也会显示模拟属性
  • @DILEEPTHOMAS 你用的是什么版本的Jest
猜你喜欢
  • 1970-01-01
  • 2019-07-16
  • 2019-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
  • 2018-08-07
  • 1970-01-01
相关资源
最近更新 更多