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
最佳答案
您可以将 setupFiles
或 setupFilesAfterEnv
添加到您的 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/