javascript - 如何使用 jest 模拟原始 const 值并恢复模拟?
问题描述
所以假设我有一个名为“config.js”的文件:
export const DELAY_SECONDS = 5;
在进行测试时:
// Ignore the delay when doing the tests.
jest.mock("/path/to/config", () => ({ DELAY_SECONDS: 0 }))
但我也想测试原始值是否有效:
it('should work with delay', () => {
// Use original value implicitly.
a_function_uses_DELAY_SECONDS()
expect(...).toBe(...)
})
我怎样才能恢复那个模拟?还是有更好的方法来实现模拟?
我在下面尝试了一些方法,但它们都不起作用:
it('should work with delay', () => {
jest.unmock() // Doesn't work at all, don't even know what does this method do.
// Use original value implicitly.
a_function_uses_DELAY_SECONDS()
expect(...).toBe(...)
})
it('should work with delay', () => {
jest.mock("/path/to/config", () => ({ DELAY_SECONDS: 5 })) // Call the mock again doesn't work
// Use original value implicitly.
a_function_uses_DELAY_SECONDS()
expect(...).toBe(...)
})
it('should work with delay', () => {
const config = require("/path/to/config").default;
config.DELAY_SECONDS = 5; // Won't work, as it is a constant, cannot modify
// Use original value implicitly.
a_function_uses_DELAY_SECONDS()
expect(...).toBe(...)
})
解决方案
您可以使用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
推荐阅读
- c# - LINQ 中哪种方法更好?
- javascript - 在开发人员控制台的 AngularJS 应用程序对象中,哪里可以找到声明的变量及其值?
- r - 构建反应数据错误:“'closure'类型的对象不是子集”
- java - 在 mysql 中选择特定表中的操作时触发电子邮件或信息
- ldap - 将用户导入 LDAP 服务器
- html - Ionic 4 - 根据用户打开页面的日期自动滚动到某个部分
- google-maps - Google Places API 响应结构已更改 - 从预测中删除了 ID 字段
- jquery-forms-plugin - 使用 jquery 表单插件时无法将附加数据(对象)发送到后端:ajaxSubmit
- sql-server - 用于查找非空值和空值的正则表达式
- echo - 使用大于 Windows 命令长度限制的输入字符串将输出回显到文件