Permalink
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
115 lines (91 sloc) 2.05 KB
layout title date excerpt categories
post
How to test process.exit with Sinon
2017-12-10 21:30:05 -4000
How to test Node.js process.exit with Sinon stubs.
sinon stub process exit nodejs test

Install Mocha and Sinon.js:

$ npm install mocha@4 sinon@4

Create the test directory and file:

$ mkdir test
$ touch test/file.js

Import assert and sinon:

// test/file.js
const assert = require('assert');
const sinon = require('sinon');

Now create a test case that stubs exit from process:

// ...
describe('process.exit', () => {
  it('is stubbed', () => {
    sinon.stub(process, 'exit');
    process.exit(1);
    assert(process.exit.isSinonProxy);
  });
});

Write your assertions with assert:

// ...
    assert(process.exit.called);
    assert(process.exit.calledWith(1));
    assert.equal(process.exit.args[0][0], 1);
// ...

Or write them with sinon:

// ...
    sinon.assert.called(process.exit);
    sinon.assert.calledWith(process.exit, 1);
// ...

Also, don't forget to restore the original function when the test is done:

// ...
  it('is stubbed', () => {
    // ...
    process.exit.restore();
  });
// ...

A good refactor tip is to move the stub and restore logic to mocha's before and after hooks:

// ...
describe('process.exit', () => {
  before(() => {
    sinon.stub(process, 'exit');
  });

  after(() => {
    process.exit.restore();
  });

  it('is stubbed', () => {
    process.exit(1);
    assert(process.exit.isSinonProxy);
    sinon.assert.called(process.exit);
    sinon.assert.calledWith(process.exit, 1);
  });
});

Lastly, you can alter the stub's behavior with callsFake:

// ...
  it('is stubbed and faked', () => {
    process.exit.callsFake(() => {
      return 'foo';
    });
    assert.equal(process.exit(), 'foo');
  });
// ...

To run the tests in your command-line:

$ node_modules/.bin/mocha # $(npm bin)/mocha

Check out the documentation for more information.