jestjs - 使用 Jest 测试一个命令行工具

标签 jestjs

我有一个将脚本公开为命令的应用程序。如何使用 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/

相关文章:

node.js - Redis 测试在通过后不退出(使用 Jest )

reactjs - 如何在 JEST 中测试 JSON.parse

javascript - 测试 React 表单组件

node.js - MongoDB-Memory-Server 使 jest 测试调试卡在 WSL 上

typescript - 没有为 ts-jest 和 puppeteer 定义浏览器

unit-testing - 使用 Enzyme + React Native + Jest 进行测试时常量未定义

vue.js - 测试 VueX 商店

reactjs - 用 Jest 模拟 React 自定义钩子(Hook)

jestjs - 开 Jest ,我如何使用 "toHaveBeenCalledWith"并且只匹配数组参数中对象的一部分?

javascript - Jest es6 模块 : unexpected module import