Giter VIP home page Giter VIP logo

mock-cli's People

Contributors

timkendrick avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

mock-cli's Issues

Help: Does the package support readline?

Could use some help! I posted my question here.

https://stackoverflow.com/questions/49348446/testing-readline-module-with-mock-cli

I am trying to create a unit test for module using readline which interpret stdin provides stdout.

Module:

#!/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)
})

Test:

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, world\n'),
  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)

It's failing the test because the output is not valid, and it's not running the .on('line) event.

process.exit() not enforced when caught

I've been finding mock-cli super useful for my current small project. However, I noticed that because it catches process.exit(), it doesn't stop execution of the code, and while at that point mock-cli will stop doing its work, the code in question won't, and in my case trigger another sanity check that will kill the process and my tests...

Here's an example of the issue:

// test.js
const mockCLI = require('mock-cli');
mockCLI(process.argv, { stdout: process.stdout, stderr: process.stderr });
require('./tested');
console.log("This should print.");
// tested.js
console.log("Killing process.")
process.exit(1);
console.log("Killing process again.")
process.exit(1);

When running node test it will output the following:

 ▼                            Start of CLI capture                            ▼ 
Killing process.
 ▲                             End of CLI capture                             ▲ 
Killing process again.

The workaround was to add a throw statement right after the process.exit() line, which doesn't seem very elegant to do as its evidently only for the mock testing. I wonder if there's a way to fix this without making a mess of the simplicity with which this utility works. I don't really know the innards of Node well enough to speculate at this point...

No stream sent on second call

No stream sent on second call

const mockCli = require('mock-cli')
const {Readable} = require('stream')
const util = require('util')
const bluebird = require('bluebird')

const 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()
}

const mockCliWrapper = (argv, stdin) => {
  return mockCli(['node', 'index', ...argv], {
    stdin: createReadableStream(stdin),
    stdout: process.stdout,
    stderr: process.stderr
  }, (error, result) => {
    if (error) throw error
    console.log(result)
  })
}

const test = async (argv, stdin) => {
  var unMockCli = mockCliWrapper(argv, stdin)
  delete require.cache[require.resolve('./index')]
  require('./index')
  await bluebird.delay(0)
  unMockCli()
}

(async () => {
  await test(['World', 'Thomas'], 'Hello World!')
  await test(['America', 'Thomas'], 'Hello America!')
})()

Here's the file I am trying to test.

// #!/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)

This is logging the following

 ▼     Start of CLI capture        ▼
 Hello Thomas!▲      End of CLI capture           ▲
{ code: 0,
  stdin: 'Hello World!',
  stdout: 'Hello Thomas!',
  stderr: '' }
 ▼     Start of CLI capture        ▼
 ▲      End of CLI capture           ▲

The required module code is not getting the second stdin for some reason.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.