javascript - 如何在 Jest 中重置模拟值?
问题描述
我正在尝试开玩笑并编写单元测试。我已经为几个函数编写了单元测试。这些函数使用从不同文件导入的常量对象。所以我嘲笑了这些常量。
describe('testing helpers', () => {
beforeEach(() => jest.resetModules());
describe('reset board', () => {
// first test using original constant values
test('with default constants', () => {
const game = {
board: [
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]
],
count: 0
};
const helper = require('./helper');
expect(helper.resetBoard()).toEqual(game);
});
// second test using mocked constant values
test('reset board', () => {
const game = {
board: [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
],
count: 0
};
jest.mock("./constants", () => ({ ROWS: 4, COLUMNS: 5 }));
const helper = require('./helper');
expect(helper.resetBoard()).toEqual(game);
});
});
describe('make move', () => {
// third test with original constant values
test('player 1 move', () => {
const testBoard = [
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]
];
const testTurn = 'YELLOW';
const testColumn = 0;
const expectedBoard = [
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0]
];
const helper = require('./helper');
helper.makeMove(testBoard, testTurn, testColumn);
expect(testBoard).toEqual(expectedBoard);
});
});
});
但是当第二个描述块中的第三个测试运行时,它会选择模拟值而不是原始值。我认为这beforeEach(() => jest.resetModules());
会重置模拟值,但它不起作用。请帮助解决这个问题。任何其他改进测试的技巧将不胜感激。
解决方案
jest.resetModules
只重置模块缓存并允许重新导入模块,它不会影响模块模拟:
重置模块注册表 - 所有必需模块的缓存。这对于隔离测试之间本地状态可能发生冲突的模块很有用。
为了使模块模拟被丢弃,jest.unmock
或者jest.dontMock
需要使用。如果这些测试的默认行为是 unmocked constants
,则可以是:
beforeEach(() => {
jest.unmock("./constants");
jest.resetModules();
});
在这种情况下,更容易在顶层导入原始实现并在需要它的测试中使用它:
const helper = require('./helper');
...
并且require
仅在需要模拟实现helper
或依赖的模块的测试中进行模拟(constants
)。beforeEach
并且仍然是可取的jest.resetModules
,jest.unmock
以便这些测试不会相互交叉污染,使用顶级的测试helper
不会受到它的影响。
推荐阅读
- python - 如何在 Python 中的 Selenium 上设置 cookie?
- python - 如何使用 pandas 数据框向绘图甘特图添加垂直线?
- python - os.path.join 用于获取级别路径
- apache-kafka - 了解kafka中间件通信
- python - 如何在同一个列表中有两个不同的排序顺序?
- mysql - 如何在 MySQL Workbench 8.0.14 中修改 mysqldump 命令参数?
- chromecast - 带有 Widevine DRM 的 Chromecast CAF
- conditional - Maximo 处理规则
- ubuntu - 如何更改仪表板管理员
- sql-server - 尝试安装 sql server express 2014 或 2008 时如何修复“库未注册”