【问题标题】:How can I mock path with path.win32 in jest?我怎样才能开玩笑地用 path.win32 模拟路径?
【发布时间】:2022-12-09 11:47:53
【问题描述】:
我希望我的测试套件像在 Windows 平台上一样工作。不幸的是,很多依赖项使用 path 模块。我想用 path.win32 实现来模拟它。但是,这种方法不起作用:
const winPath = require("path").win32;
jest.mock("path", () => winPath);
ReferenceError:初始化前无法访问“winPath”
这样做的正确方法是什么?
【问题讨论】:
标签:
node.js
jestjs
mocking
【解决方案1】:
jest.mock() 应该可以。下面的示例显示了如何模拟 win32.normalize() 方法。
const winPath = require("path").win32;
jest.mock('path', () => {
return {
...(jest.requireActual('path') as typeof import('path')),
win32: {
normalize: jest.fn(),
}
}
})
describe('74717157', () => {
test('should pass', () => {
winPath.normalize.mockImplementation(() => 'override the original implementation')
expect(jest.isMockFunction(winPath.normalize)).toBeTruthy();
expect(winPath.normalize()).toBe('override the original implementation')
})
})
测试结果:
PASS stackoverflow/74717157/index.test.ts (10.557 s)
74717157
✓ should pass (1 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 14.116 s