5

I found out a good way to mock named exports, based on this answer: https://stackoverflow.com/a/38414108/4644522

codeToTest.js:

import {someMethod} from './someNamedExports'
export default () => someMethod()

codeToTestSpec.js:

import * as someNamedExports from './someNamedExports'
import codeToTest from './codeToTest

sinon.stub(someNamedExports, 'someMethod')
codeToTest()
someNamedExports.someMethod.should.have.been.called
someNamedExports.someMethod.restore()

And this works as expected.

However, I seem to be running into issues with default exports. Here is what I have tried:

codeToTest.js:

import someDefaultExport from './someDefaultExport
export default () => someDefaultExport()

codeToTestSpec.js:

import * as someDefaultExport from './someDefaultExport'
import codeToTest from './codeToTest

sinon.stub(someDefaultExport, 'default')
codeToTest()
someDefaultExport.default.should.have.been.called
someDefaultExport.default.restore()

It doesn't seem to be stubbing it as expected and complains about someDefaultExport.default not being defined when trying to restore.

Am I missing something or is this a possible bug with sinon?

eliw00d
  • 321
  • 2
  • 12
  • That should totally work, default exports are just exports with the name `default` indeed. What do the transpiled scripts look like (including `someDefaultExport.js`)? – Bergi Sep 07 '17 at 21:43
  • So, I noticed that if I change my code to `import * as someDefaultExport from './someDefaultExport'` and then change references of `someDefaultExport()` to `someDefaultExport.default()` the test will work as expected. Originally it was `import someDefaultExport from './someDefaultExport'`. But that is a change I don't want to make to the code being tested. – eliw00d Sep 07 '17 at 22:08
  • 1
    Ai, that's weird, I didn't think transpilers made this a difference. Can you try `import {default as someDefaultExport} from './someDefaultExport'` in the tested code? That might let you keep the `someDefaultExport` identifier but be an acceptable change. – Bergi Sep 07 '17 at 22:36
  • That seems to work, although having to change all of the source code to match will be painful. By the way, how would you mock exports that are values instead of functions? I tried `someDefaultExport.someValue = someOtherValue` and it doesn't change in the tested code. – eliw00d Sep 08 '17 at 16:00
  • 1
    I have the very same problem. Did you ever find a solution? – waldgeist Jan 07 '18 at 16:47
  • We ended up switching to Jest over Mocha/Sinon and have not had issues. – eliw00d Jan 08 '18 at 20:56

0 Answers0