我有一个应用程序,它将脚本公开为命令.如何使用jest测试此脚本.更具体地说,如何使用jest执行此脚本然后应用相应的期望?该脚本不会导出任何函数,它只包含一串顺序执行的代码行.
您可以将代码包装在main函数中,将其导出,并且仅在从命令行执行模块时运行该函数,然后为其编写测试。一个简化的例子可以是:
// script.js
const toUpper = text => text.toUpperCase();
module.exports.toUpper = toUpper;
// It calls the function only if executed through the command line
if (require.main === module) {
toUpper(process.argv[2]);
}
Run Code Online (Sandbox Code Playgroud)
然后toUpper从测试文件中导入函数
// script.test.js
const { toUpper } = require('./script');
test('tranforms params to uppercase', () => {
expect(toUpper('hi')).toBe('HI');
});
Run Code Online (Sandbox Code Playgroud)
请参阅节点:访问主模块
| 归档时间: |
|
| 查看次数: |
723 次 |
| 最近记录: |