25

sinon.spy takes 2 parameters, object and function name.

I have a module as listed below:

module.exports = function xyz() { }

How do I define a spy for xyz? I don't have object name to use.

Thoughts?

1 Answer 1

55

The above actually doesn't work if you're using the ES6 modules import functionality, If you are I've discovered you can actually spy on the defaults like so.

// your file
export default function () {console.log('something here');}

// your test
import * as someFunction from './someFunction';
spyOn(someFunction, 'default')

As stated in http://2ality.com/2014/09/es6-modules-final.html

The default export is actually just a named export with the special name default

So the import * as someFunction gives you access to the whole module.exports object allowing you to spy on the default.

3
  • 2
    anyone found a way to do this using module.exports ? Commented Sep 14, 2017 at 14:28
  • @PimHeijden Check out module rewire. And a nice blog post on how to use it.
    – thalisk
    Commented Dec 14, 2017 at 13:02
  • This will not work, the default property of the exported module is not writable. Commented Oct 14, 2019 at 15:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.