How do I unit test using sinon?

126 views Asked by At

A.js

const func2 = () => 'world';

module.exports = {func2}

Util.js

const {func2} = require("./A");

const func1 = () => {
    return 'hello ' + func2();  // <= use the module
  }

  module.exports = { func1 }

 

Util.test.js

const sinon = require('sinon');
const {func1} = require('./util');
const a = require('./A');
const chai = require("chai");
const expect = chai.expect;

describe('func1', () => {
  it('should work', () => {
    const stub = sinon.stub(a, 'func2').returns('everyone');
    expect(func1()).to.be.equal('hello everyone');  // Success!
  });
});

Getting assertion failure... Sinon stub func2 is not stubbing

AssertionError: expected 'hello world' to equal 'hello everyone' at Context. (test\util.test.js:10:27) at processImmediate (internal/timers.js:456:21)

  • expected - actual

-"hello world" +"hello everyone"

2

There are 2 answers

0
andreyunugro On

If you still want it: change the implementation at Util.js to something like this.

const a = require("./a");

const func1 = () => {
  return 'hello ' + a.func2();
}

module.exports = { func1 };

Proof:

$ npx mocha util.test.js 


  func1
    ✓ should work


  1 passing (3ms)

Note: it is still not dependency injection but little change on how func2 get called.

0
Lin Du On

You can stub out func2 with Link Seams. This is the CommonJS version, so we will be using proxyquire to construct our seams.

E.g.

a.js:

const func2 = () => 'world';

module.exports = { func2 };

util.js:

const { func2 } = require('./a');

const func1 = () => {
  return 'hello ' + func2();
};

module.exports = { func1 };

util.test.js:

const sinon = require('sinon');
const chai = require('chai');
const proxyquire = require('proxyquire');
const expect = chai.expect;

describe('func1', () => {
  it('should work', () => {
    const func2Stub = sinon.stub().returns('everyone');
    const { func1 } = proxyquire('./util.js', {
      './a': {
        func2: func2Stub,
      },
    });
    expect(func1()).to.be.equal('hello everyone');
  });
});

unit test result:

  func1
    ✓ should work (1794ms)


  1 passing (2s)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   85.71 |      100 |      50 |     100 |                   
 a.js     |   66.67 |      100 |       0 |     100 |                   
 util.js  |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------