The tested file uses a function that is imported from another file
import {myFunc} from './myFile'
How can I mock return value for this function in my tests for this file? I'm using jest.
There are two ways to mock functions: Either by creating a mock function to use in test code, or writing a manual mock to override a module dependency.
Jest can be used to mock ES6 classes that are imported into files you want to test. ES6 classes are constructor functions with some syntactic sugar. Therefore, any mock for an ES6 class must be a function or an actual ES6 class (which is, again, another function). So you can mock them using mock functions.
Function mock using jest. The simplest and most common way of creating a mock is jest. fn() method. If no implementation is provided, it will return the undefined value. There is plenty of helpful methods on returned Jest mock to control its input, output and implementation.
In order to mock named exports in Jest, you need to import all named exports from a file with an * and assign jest. fn to the method that needs to be mocked. mockImplementation expects a callback function to be passed that describes the implementation.
This is what worked for me, I'm not sure if it's a good practice tho:
import * as myFile from "./myFile";
jest.mock("./myFile");
myFile.myFunc = jest.fn().mockImplementation(() => {
return "Some Value";
});
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