2

I have a function with depends on another function and instead of testing the dependency I just want to test specific results of that dependency function. However, when I stub the function nothing happens and the return result is as if I never stubbed the function in the first place.

Example code:

// File being tested
function a() {
  let str = 'test';
  return b(str);
}

function b(str) {
  return str + str;
}

module.exports = {
  a: a,
  b: b
};

// Test file
let test = require('file.to.test.js');

it('should correctly stub the b function', () => {
  sinon.stub(test, 'b').returns('asdf');
  let result = test.a();

  // Expected 
  assert(result === 'asdf');

  // Received
  assert(result === 'testtest');
});

1 Answers1

1

Your stub have no expected effect because you've stubbed property of imported object. However, function a() keeps calling the original function b(), because it calls function, not an object method.

If you change the code the way that there is an object with property b and a, and property a, calls property b, then it would work the expected way:

const x = {};
x.a = () => {
  let str = 'test';
  return x.b(str);
}

x.b = (str) => {
  return str + str;
}

module.exports = x;

Also, have a look at this answer, it describes similar problem.

Alejandro
  • 5,834
  • 1
  • 19
  • 36