【问题标题】:Javascript CLI: how to invoke bin file so that I can run integration tests with JestJavascript CLI:如何调用 bin 文件以便我可以使用 Jest 运行集成测试
【发布时间】:2019-11-10 16:28:27
【问题描述】:

我创建了一个命令行界面,它可以对 Google 图书进行 API 调用,并允许用户使用关键字搜索图书。搜索返回包含五本书的列表,其中包括可用于将记录保存到阅读列表(写入本地文件)的书籍 ID。

我想创建一些集成测试,但我不确定如何使用我设置的 bin 文件“调用”程序。最终我想测试用户输入是否会导致程序的正确响应,但我需要测试的第一件事是初始命令运行程序。

非常感谢任何帮助!

package.json

{
  ...

  "bin": {
    "books-cli": "bin/books-cli"
  },

  ...
}

bin/books-cli

#!/usr/bin/env node
require('../')()

index.js

module.exports = () => {
  const args = minimist(process.argv.slice(2));
  let command = args._[0] || 'help';

  if (args.help || args.h) {
    command = 'help';
  }

  if (args.version || args.v) {
    command = 'version';
  }

  switch (command) {
    case 'search':
      require('./commands/search')(args);
      break;
    case 'save':
      require('./commands/save')(args);
      break;
    case 'list':
      require('./commands/list')(args);
      break;
    case 'help':
      require('./commands/help')(args);
      break;
    case 'version':
      require('./commands/version')(args);
      break;
    default:
      console.error(
        `Sorry, "${command}" is not a valid command. Please type 'books-cli help' to see the help menu.`
      );
      break;
  }
};

【问题讨论】:

    标签: javascript jestjs command-line-interface integration-testing


    【解决方案1】:

    您可以从 package.json 获取二进制文件的名称并生成 child_process,然后编写断言

    例如(未测试):

    books-cli.spec.js
    const { bin: { books-cli }} = require('package.json');
    const { exec } = require('child_process');
    
    describe('books-cli', () => {
      describe('help', () => {
        let error;
        let result;
        beforeAll(done => {
          exec(`${books-cli} help`, (err, stdout, stderr) => {
            error = stderr;
            result = stdout;
            // let jest know when the process finishes execution
            // so all the tests below will be run with error and 
            // result populated
            done();
          });
        });
        it('should not result an error', () => {
          expect(error).toEqual('.....');
        });
    
        it('should output helpful information', () => {
          expect(result).toEqual('....');
        });
    
        // describe the rest of the commands
        describe('search');
        describe('save');
      });
    });
    

    【讨论】:

    • 非常感谢!我会试一试的。
    猜你喜欢
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 2022-12-24
    • 2021-10-14
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 2015-12-26
    相关资源
    最近更新 更多