jbs87
jbs87

Reputation: 55

How to mock nested dependencies in NodeJS

I have a Module a

const b = require(./b);

function aGetResult() {
  return b.getInfo();
}

Module B

const c = require(./c);
    
function getInfo() {
  return getDetailInfo();
}

function getDetailInfo() {
    const result = c.getApiResult();
    return result
}

Module C

function getApiResult() {
  return api.get(/test/1);
}

I've written a test for module A but am running into an issue with stubbing dependencies.I just want to stub c.getApiResult() and not b.getInfo() or b.getDetailInfo(). I've tried selectively stubbing using proxyquire but am having issues. Any help?

Upvotes: 2

Views: 1815

Answers (1)

Lin Du
Lin Du

Reputation: 102207

You should use Globally override require of proxyquire package.

a depends b, b depends on c. Now you want to mock the indirect c dependency instead of direct b dependency when you test a. It's NOT recommended to do this. But anyway, here is the solution:

E.g.

a.js:

const b = require('./b');

function aGetResult() {
  return b.getInfo();
}

exports.aGetResult = aGetResult;

b.js:

const c = require('./c');

function getInfo() {
  return getDetailInfo();
}

function getDetailInfo() {
  const result = c.getApiResult();
  return result;
}

module.exports = { getInfo };

c.js:

const api = {
  get(url) {
    return 'real result';
  },
};

function getApiResult() {
  return api.get('/test/1');
}

module.exports = { getApiResult };

a.test.js:

const proxyquire = require('proxyquire');
const { expect } = require('chai');
const sinon = require('sinon');

describe('63275147', () => {
  it('should pass', () => {
    const stubs = {
      './c': {
        getApiResult: sinon.stub().returns('stubbed result'),
        '@global': true,
      },
    };
    const a = proxyquire('./a', stubs);
    const actual = a.aGetResult();
    expect(actual).to.be.eq('stubbed result');
    sinon.assert.calledOnce(stubs['./c'].getApiResult);
  });
});

unit test result:

  63275147
    ✓ should pass (2630ms)


  1 passing (3s)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   83.33 |      100 |      60 |   83.33 |                   
 a.js     |     100 |      100 |     100 |     100 |                   
 b.js     |     100 |      100 |     100 |     100 |                   
 c.js     |      50 |      100 |       0 |      50 | 3-8               
----------|---------|----------|---------|---------|-------------------

Upvotes: 5

Related Questions