Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest mock an object

I need to mock an object, config.js, rather than mocking a function as normal. I have -

//config.js . 
export default {
   foo: 'bar'
}

I have tried -

import config from './config';
jest.mock('./config');
config.mockReturnValue({
   foo: 'zed'
})

also -

import config from './config';
jest.mock('./config');
config.mockImplentation(() => ({
   foo: 'zed'
}));

But its not mocking anything, and I am getting the config file as normal.

What am I doing wrong?

like image 329
andy mccullough Avatar asked May 14 '18 10:05

andy mccullough


1 Answers

The second parameter of jest.mock accepts a factory which you can use to return the object you want to mock:

jest.mock('./config', () => ({ foo: 'zed' }))

or you can modify the object:

import config from './config';
config.foo = 'zed'

The problem with your approach is that it would only work for modules that return functions.

Jest Documentation - jest.mock(moduleName, factory, options)

like image 157
Andreas Köberle Avatar answered Sep 26 '22 23:09

Andreas Köberle