Sinon Stub not working for exported function
Asked Answered
O

1

7

Sinon doesn't seem to be stubbing a method from an imported file. Is it to do with exporting consts?

I see "Received ORIGINAL MESSAGE" in the console.log.

Main.js

import * as otherActions from 'filters/actions/Other.actions';

describe('filter actions', () => {

    it('should log STUBBED MESSAGE', () => {   
      sinon.stub(otherActions, 'logMessage').callsFake(m => console.log('STUBBED Message'));
      const compiled = otherActions.doSomethingAndLogMessage(5, 5);
      compiled(message => console.log(`RECEIVED ${message}`), () => {});
    });

});

Other.actions.js

export const logMessage = () => console.log("ORIGINAL MESSAGE");

export const doSomethingAndLogMessage = (categoryId, size) => (dispatch, getState) => {
  dispatch(logMessage());
};
Ophthalmia answered 23/7, 2018 at 15:46 Comment(3)
What version of sinon are you using?Strickman
I'm using version 5.0.10Ophthalmia
Does this answer your question? How to stub exported function in ES6?Nympha
S
5

The problem is occurring because you are stubbing the function in the exported module, when referenced in the module context. You are not stubbing when referencing it raw from inside the module. There are many ways to fix this, but I think all will require you to change your production code a bit.

One suggestion is this:

Other.actions.js

export const logger = { message: () => console.log("ORIGINAL MESSAGE") };

Main.js

import * as otherActions from 'filters/actions/Other.actions';

...
sinon.stub(otherActions.logger, 'message')
  .callsFake(m => console.log('STUBBED Message'));

The important thing is that you create the stub in a context that is available to the module under test.

And another general comment is that typically, you don't want to mock or stub functions or methods in the module you are testing. Typically, the unit of unit testing refers to a module. And so, if you find the need to stub out something in the same module you are testing, then I'd suggest that your module boundaries are not correct.

Strickman answered 23/7, 2018 at 19:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.