ima*_*00b 5 javascript unit-testing module mocking node.js
我有一个模块,它不应该直接从命令行使用 Node.js 调用。为此,我正在检查文档中指示的主模块:
if (require.main === module) {
console.error('This module cannot be run from the command line.');
} else {
// Here the module logic...
}
Run Code Online (Sandbox Code Playgroud)
现在我正在为这个模块编写单元测试(如果重要的话,使用 Mocha/Chai),我想模拟直接从命令行调用模块的情况,当错误应该打印到 stderr 时。
其余的逻辑已经在测试中,但require.main === module
我的单元测试无法覆盖分支。我想象解决这个问题的最干净的方法是require.main
在模块内部模拟,但我不知道如何做到这一点。我们已经使用 proxyquire 来模拟依赖关系,但在这种情况下它没有帮助。
任何建议如何处理这个问题?
已经三年了,但我能够模拟这种情况。
\n概念:存根/模拟比较函数,在require.main
和之间进行比较module
。
对于下面的示例:我使用模块:rewire、sinon、chai、mocha 和 nyc。
\n有这个index.js
\n// File: index.js (original)\nif (require.main === module)) {\n console.log(\'Run directly\');\n} else {\n console.log(\'Run NOT directly\');\n}\n
Run Code Online (Sandbox Code Playgroud)\n我创建了包含比较 2 个输入的函数的助手。
\n// File: helper.js\nfunction runDirectly(a, b) {\n // Suppose:\n // a: require.main\n // b: module\n return (a === b);\n}\n\nmodule.exports = { runDirectly };\n
Run Code Online (Sandbox Code Playgroud)\n我将索引修改为类似这样的内容。
\n// File: index.js (modified)\nconst helper = require(\'./helper.js\');\n\nif (helper.runDirectly(require.main, module)) {\n console.log(\'Run directly\');\n} else {\n console.log(\'Run NOT directly\');\n}\n
Run Code Online (Sandbox Code Playgroud)\n当我直接从命令行尝试时,它仍然可以正确运行。
\n$ node index.js\nRun directly\n$\n
Run Code Online (Sandbox Code Playgroud)\n我创建了这个规范文件。
\n$ node index.js\nRun directly\n$\n
Run Code Online (Sandbox Code Playgroud)\n然后当我运行测试和覆盖率时,结果如下。
\n$ npx nyc mocha index.spec.js \n\n\n Index\n \xe2\x9c\x93 simulate run directly\n \xe2\x9c\x93 simulate run NOT directly\n\n\n 2 passing (45ms)\n\n---------------|---------|----------|---------|---------|-------------------\nFile | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s \n---------------|---------|----------|---------|---------|-------------------\nAll files | 96.77 | 100 | 83.33 | 96.77 | \n helper.js | 50 | 100 | 0 | 50 | 10 \n index.js | 100 | 100 | 100 | 100 | \n index.spec.js | 100 | 100 | 100 | 100 | \n---------------|---------|----------|---------|---------|-------------------\n$\n
Run Code Online (Sandbox Code Playgroud)\n现在index.js已经100%覆盖,helper.js很容易测试。:)
\n 归档时间: |
|
查看次数: |
612 次 |
最近记录: |