Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest - mock function, that is imported from another file

Tags:

reactjs

jestjs

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.

like image 839
Anna Avatar asked Apr 30 '19 12:04

Anna


People also ask

How mock a function from another file in 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.

How do you mock an import in Jest?

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.

How do you mock a particular function in Jest?

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.

How do you mock a named export in Jest?

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.


1 Answers

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";
 });
like image 77
Anna Avatar answered Oct 19 '22 06:10

Anna