Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to spy on a default exported function with Jest?

Suppose I have a simple file exporting a default function:

// UniqueIdGenerator.js const uniqueIdGenerator = () => Math.random().toString(36).substring(2, 8);  export default uniqueIdGenerator; 

Which I would use like this:

import uniqueIdGenerator from './UniqueIdGenerator'; // ... uniqueIdGenerator(); 

I want to assert in my test that this method was called while keeping the original functionality. I'd do that with jest.spyOn however, it requires an object as well as a function name as parameters. How can you do this in a clean way? There's a similar GitHub issue for jasmine for anyone interested.

like image 823
thisismydesign Avatar asked Jan 17 '19 23:01

thisismydesign


People also ask

How do I spy on exported function jest?

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 do in react?

Export default means you want to export only one value the is present by default in your script so that others script can import that for use. This is very much necessary for code Reusability.

What does export default mean js?

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.


2 Answers

one could also mock the import and pass the original implementation as mock implementation, like:

import uniqueIdGenerator from './UniqueIdGenerator'; // this import is a mock already  jest.mock('./UniqueIdGenerator.js', () => {   const original = jest. requireActual('./UniqueIdGenerator')   return {      __esModule: true,      default: jest.fn(original.default)   } })  test(() => {   expect(uniqueIdGenerator).toHaveBeenCalled() }) 
like image 41
alex.spri Avatar answered Sep 17 '22 11:09

alex.spri


I ended up ditching the default export:

// UniqueIdGenerator.js export const uniqueIdGenerator = () => Math.random().toString(36).substring(2, 8); 

And then I could use and spy it like this:

import * as UniqueIdGenerator from './UniqueIdGenerator'; // ... const spy = jest.spyOn(UniqueIdGenerator, 'uniqueIdGenerator'); 

Some recommend wrapping them in a const object, and exporting that. I suppose you can also use a class for wrapping.

However, if you can't modify the class there's still a (not-so-nice) solution:

import * as UniqueIdGenerator from './UniqueIdGenerator'; // ... const spy = jest.spyOn(UniqueIdGenerator, 'default'); 
like image 80
thisismydesign Avatar answered Sep 20 '22 11:09

thisismydesign