我有一个将脚本公开为命令的应用程序。如何使用 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]);
}
然后导入
toUpper
测试文件中的函数// script.test.js
const { toUpper } = require('./script');
test('tranforms params to uppercase', () => {
expect(toUpper('hi')).toBe('HI');
});
见 Node: Accessing the main module
关于jestjs - 使用 Jest 测试一个命令行工具,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40628927/