你可以使用
jest.doMock(moduleName, factory, options)
.
例如。
config.js
:
export const DELAY_SECONDS = 5;
main.js
:
import { DELAY_SECONDS } from './config';
function main() {
return DELAY_SECONDS;
}
export { main };
main.test.js
:
describe('64473533', () => {
beforeEach(() => {
jest.resetModules();
});
it('should work with delay - original', () => {
const { main } = require('./main');
const actual = main();
expect(actual).toBe(5);
});
it('should work with delay - mocked', () => {
jest.doMock('./config', () => ({ DELAY_SECONDS: 0 }));
const { main } = require('./main');
const actual = main();
expect(actual).toBe(0);
});
});
单元测试结果:
PASS src/stackoverflow/64473533/main.test.js
64473533
â should work with delay - original (445ms)
â should work with delay - mocked (2ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
config.js | 100 | 100 | 100 | 100 | |
main.js | 100 | 100 | 100 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 3.694s