Skip to content

b4dnewz/process-test

Repository files navigation

process-test

Easy way to test command line applications

NPM version Build Status Coverage percentage

This project is mainly based on coffee but implemented in TypeScript with no dependencies.

Install

npm install @b4dnewz/process-test

Usage

You can use it in your tests with any framework to test your code execution:

import {fork, spawn} from "@b4dnewz/process-test"

// Spawn a nodejs process
it("will spawn node script", (done) => {
  fork("./test.js", ["foo", "bar"], {})
    .expect("stdout", /foo bar/)
    .expect("code", 0)
    .end(done);
})

// Spawn a system command
it("will spawn system command", (done) => {
  spawn("node", ["--version"], {})
    .expect("stdout", process.version)
    .expect("code", 0)
    .end(done);
})

File used in usage example test.js

#!/usr/bin/env node

const argv = process.argv.slice(2).join(" ")
process.stdout.write(argv);

API

fork

This method is used specifically to spawn new Node.js process using the given file path, arguments and options.

// fork(binPath)
fork("./test.js")

// fork(binPath, args)
fork("./test.js", ["--foo", "bar"])

// fork(binPath, args, options)
fork("./test.js", ["foo"], { env: {} })

spawn

This method spawns a new process using the given command, arguments and options.

// spawn(binPath)
spawn("node")

// spawn(binPath, args)
spawn("node", ["--version"])

// spawn(binPath, args, options)
spawn("ls", ["-l"], {
  cwd: "/home"
})

All the methods returns a test Process class which has the following method to interact with the process and the result:

expect(type, expectation)

This method is used to set an expectation of the process result.

spawn("node", ["--version"])
  .expect("stdout", new RegExp(process.version))
  .expect("code", 0);

notExpect(type, expectation)

This method is used to set an expectation of the process result.

spawn("node", ["--version"])
  .notExpect("code", 1);

License

MIT © Filippo Conti