javascript - 所有测试文件中的 Jest Mock 用户模块

标签 javascript reactjs unit-testing jestjs

Is there a way to make it so that jest always mocks my modules so I don't need to include it in all my jest tests?

目前我有一个配置文件

// src/__mocks__/config.js 
export default {
  dbConfig: 'TestDBConfiguration'
};

// src/config.js
export default {
  dbConfig: ... // Some other stuff
};

要运行我的单元测试,我必须使用模拟的config.js。 目前,在我的所有单元测试中,我必须包含 jest.mock('../config');

// org.test.js
jest.mock('../../config');
import db from '../db';              // This internally uses the config file
import otherFile from '../otherFile'; // This also uses the config file

// Code that calls both db/otherFile

有时,当我创建测试时,我可能会忘记包含jest.mock('../config'),这也是我希望将其包含在所有测试中的原因之一。

我已经考虑启用automock,但它似乎反而破坏了我的测试。 https://facebook.github.io/jest/docs/en/configuration.html#automock-boolean

最佳答案

您可以将 setupFilessetupFilesAfterEnv 添加到您的 jest 配置中,以便在所有测试之前运行。

https://jestjs.io/docs/configuration#setupfiles-array

// package.json
...
"jest": {
  "setupFiles": "./src/setupTests.js"
}

// setupTests.js
jest.mock('config'); // Path to config file

关于javascript - 所有测试文件中的 Jest Mock 用户模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49685265/

相关文章:

unit-testing - 无法读取未定义单元测试 enzyme 的属性 'contextTypes'

javascript - 无法通过javascript更改html属性

php - 当用户关闭(弹出)窗口时调用一些 JavaScript

javascript - 使用 React.js 和 Material-UI 简化样式组件媒体查询

reactjs - React 和 Socket.io | useState 在输入中 onChange 生成新的套接字连接

具有类型和值参数化的 C++ 单元测试框架

javascript - 在我的案例中如何解决 'undefined is not a function'

javascript - Sequelize 树中的连接数据

javascript - 为什么 ReactDOMServer 和 ReactDOM 给出 "root.hydrate is not a function"错误

javascript - 关闭 ESLint 规则(在 React 应用程序中,使用 WebStorm)