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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With