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.
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 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.
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.
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() })
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');
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