【问题标题】:Capture stdout and stderr to test Node.js CLI捕获标准输出和标准错误以测试 Node.js CLI
【发布时间】:2017-01-31 04:37:52
【问题描述】:

使用another answer 中概述的技术,我能够为--help 开关编写测试:

const expect = require('chai').expect
const exec = require('child_process').exec
const cli = './cli.js'

describe('help', function () {
  var capturedStdout
  var capturedStderr
  // http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html
  // var cmd = cli + " --help 1>&2"
  var cmd = cli + ' --help'

  before(function (done) {
    exec(cmd, function (error, stdout, stderr) {
      if (error) done(error)
      capturedStdout = stdout
      capturedStderr = stderr
      done()
    })
  })

  it('should succeed', () => {
    expect(capturedStderr).be.empty
  })

  it('should have some usage instructions', () => {
    expect(capturedStdout).to.match(/Usage: words \[options] \[pattern]/)
  })

  it('should show a sematic version number', () => {
    // http://rubular.com/r/lTC1wu95jq
    expect(capturedStdout).to.match(/v\d+\.\d+\.\d+/)
  })

  it('should have some examples', () => {
    expect(capturedStdout).to.match(/Examples:/)
  })
})

我遇到了两个问题:

  1. 一个开关有 45 行。
  2. 如果我为不同的开关添加另一个describe 块,例如--version,则会收到以下错误:Error: done() called multiple times

解决方案是将测试移到另一个文件中。

有没有更好的方法来做我想做的事?我要做的就是在测试 stdout、stderr 和退出状态时重复运行我的可执行文件。

【问题讨论】:

    标签: node.js testing command-line-interface chai


    【解决方案1】:

    不回答您的整个问题,但您缺少退货声明

    before(function (done) {
        exec(cmd, function (error, stdout, stderr) {
          if (error) { 
            return done(error)
          }
    

    【讨论】:

      猜你喜欢
      • 2018-11-25
      • 2013-05-11
      • 1970-01-01
      • 2018-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      相关资源
      最近更新 更多