timkendrick / mock-cli Goto Github PK
View Code? Open in Web Editor NEWCLI capture tool for testing command-line apps
CLI capture tool for testing command-line apps
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.
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
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.