Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to spy on a default exported function

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?

like image 881
reza Avatar asked Oct 01 '15 15:10

reza


People also ask

How do you spy on an exported function?

To spy on an exported function in jest, you need to import all named exports and provide that object to the jest. spyOn function. That would look like this: import * as moduleApi from '@module/api'; // Somewhere in your test case or test suite jest.

What does export default class mean?

Export Default is used to export only one value from a file which can be a class, function, or object. The default export can be imported with any name.

What is jest spy function?

Mock functions are also known as "spies", because they let you spy on the behavior of a function that is called indirectly by some other code, rather than only testing the output. You can create a mock function with jest. fn() . If no implementation is given, the mock function will return undefined when invoked.


1 Answers

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.

like image 88
Benjamin Hughes Avatar answered Sep 22 '22 03:09

Benjamin Hughes