使用Jest测试命令行工具

时间:2016-11-16 09:53:52

标签: jestjs

我有一个应用程序,它将脚本公开为命令。如何使用jest测试此脚本。更具体地说,如何使用jest执行此脚本然后应用相应的期望?该脚本不会导出任何函数,它只包含一串按行执行的代码行。

1 个答案:

答案 0 :(得分:1)

您可以将代码包装在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