Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinon Stub not working for exported function

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());
};
like image 887
Sebastian Patten Avatar asked Oct 16 '22 15:10

Sebastian Patten


1 Answers

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.

like image 195
Andrew Eisenberg Avatar answered Nov 04 '22 00:11

Andrew Eisenberg