使用模拟 CLI 测试读取线模块



我正在尝试使用readline为模块创建一个单元测试,该测试解释stdin提供stdout。

模块:

#!/usr/bin/env node
const args = process.argv.slice(2)
var readline = require('readline')
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
})
rl.on('line', (line) => {
  process.stdout.write(line.replace(args[0], args[1]) + 'n')
}).on('close', () => {
  process.exit(0)
})

测试:

var mockCli = require('mock-cli')
var assert = require('assert')
var util = require('util')
var Readable = require('stream').Readable
function createReadableStream(input, callback) {
  input = input || null;
  function ReadableStream(options) {
    Readable.call(this, options);
  }
  util.inherits(ReadableStream, Readable);
  ReadableStream.prototype._read = function(size) {
    if (callback) { callback(input); }
    this.push(input);
    input = null;
  };
  return new ReadableStream();
}
var argv = ['node', './index.js', 'world', 'thomas']
var stdio = {
  stdin: createReadableStream('Hello, worldn'),
  stdout: process.stdout, // Display the captured output in the main console
  stderr: process.stderr // Display the captured error output in the main console
}
var kill = mockCli(argv, stdio, (error, result) => {
  if (error) throw error
  var exitCode = result.code // Process exit code
  var stdout = result.stdout // UTF-8 string contents of process.stdout
  var stderr = result.stderr // UTF-8 string contents of process.stderr
  assert.equal(exitCode, 0)
  assert.equal(stdout, 'Hello, thomas!n')
  assert.equal(stderr, '')
})
// Execute the CLI task
require('./index')
// Kill the task if still running after one second
setTimeout(kill, 1000)

它未通过测试,因为输出无效,并且未运行 .on('line) 事件。

我将代码切换为使用 get-stdin 而不是 readline 它有效!

// #!/usr/bin/env node
const getStdin = require('get-stdin')
const args = process.argv.slice(2)
getStdin().then(str => {
  try {
    if (str === '') return process.exit(0)
    const pattern = new RegExp(args[0], 'gm')
    process.stdout.write(str.replace(pattern, args[1]))
    return process.exit(0)
  } catch (e) {
    return process.exit(1)
  }
}).catch(console.log)

最新更新