Sinon: Stubbing method in same file doesn't work

Created on 5 Oct 2016  ·  3Comments  ·  Source: sinonjs/sinon

I'm trying to unit test a function in a file while stubbing another function in the SAME file, but the mock is not being applied and the real method is being called. Here's an example:

// file: 'foo.js'

export function a() {
   // .....
}

export function b() { 
   let stuff = a(); // call a
   // ...do stuff
}

And my test:

import * as actions from 'foo';

const aStub = sinon.stub(actions, 'a').returns('mocked return');
actions.b(); // b() is executed, which calls a() instead of the expected aStub()

All 3 comments

Think about how this would look in standard ES5. Each function is exported with a certain name on the exports object, but it is also internally referenceable using the function name. We are talking about two different references. When stubbing you are changing the external reference. The internal reference is kept the same. You cannot change it, except if you create an explicit dependency injector (like a setter function for internal use). This is not a bug, but a feature of JavaScript.

is there any workaround about this???It's quite common to get into this kind of issue when testing a nodejs file.

This is covered in our documentation, in the how to section:
http://sinonjs.org/how-to/link-seams-commonjs/

Was this page helpful?
0 / 5 - 0 ratings