How to spy on a default exported function

reza picture reza · Oct 1, 2015 · Viewed 12.5k times · Source

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?

Answer

Benjamin Hughes picture Benjamin Hughes · Nov 12, 2015

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.