seansylee
seansylee

Reputation: 56

How to mock a single utility function globally using jest

Suppose in my util.js I have

export function foo(){ ... do something}
export function bar(){ ... do something}
...

And in various components I utilize foo

//Foo1.component.js

import { foo } from './util'A

... do something using foo.
//Foo2.component.js

import { foo } from './util'A

... do something using foo.

etc..

How can I go about mocking this, in Foo1.test.js for example.

Even better, is there way that I can just 'hijack' this foo import maybe from the jest.config. in the moduleNameMapper Maybe?

So that it is already mocked for all tests Foo1.test.js and Foo2.test.js?

Upvotes: 1

Views: 6813

Answers (1)

Tunmise Ogunniyi
Tunmise Ogunniyi

Reputation: 2573

Yes, there is a way to mock modules in test environment.

If you want to mock the modules in specific test files, you can try just the jest.mock() function. For example, mocking the foo method in Foo1.component.js test file would go like this:

// Foo1.component.test.js

jest.mock('./path/to/utils.js', () => ({
  foo: () => { // custom implementation for test env }
  bar: () => { // custom implementation for test env if needed }
}));

// The foo imported below has the custom implementation for test env
import { foo } from './util';

The other option is to create a mock module, I think this better suite your need. In the folder where utils.js is located, create a __mocks__ folder, under which you would add a file utils.js(the same name as the module to be mocked), in that file, you can compose the mock behavior for the util.js module. For example:

// __mocks__/utils.js
export function foo(){ ... mock implementation}
export function bar(){ ... mock implementation}

Whenever you need those mock implementation in your test files, just call the the jest.mock method with the path to the module. For example:

// Foo1.component.test.js

jest.mock('./path/to/utils.js');

// The foo imported below has the custom implementation for test env
import { foo } from './util';

Links:

Upvotes: 3

Related Questions