【问题标题】:How do I mock Node.js running time operating system in a unit test for `Path` module?如何在“Path”模块的单元测试中模拟 Node.js 运行时操作系统?
【发布时间】:2023-02-15 16:40:55
【问题描述】:
node:path 模块的默认操作因运行 Node.js 应用程序的操作系统而异。 See more
// On POSIX:
path.basename('C:\\temp\\myfile.html');
// Returns: 'C:\\temp\\myfile.html'
//On Windows:
path.basename('C:\\temp\\myfile.html');
// Returns: 'myfile.html'
为了在我的本地机器上测试 POSIX 和 Windows 操作系统,我必须在单元测试中模拟 Node.js 运行时操作系统。
有没有办法做到这一点?多谢。
【问题讨论】:
标签:
node.js
unit-testing
path
mocking
【解决方案1】:
最后,我得到了proxyquire的解决方案:
const path = require('path');
const proxyquire = require('proxyquire');
const rule = proxyquire('../../../lib/rules/no-index', {
path: { ...path.win32, '@global': true },
});
在 proxyquire 的帮助下,我可以模拟 path 库并使其在我的 mac 上运行时表现得像在 Windows 上一样,而无需更改我的源代码。