Search code examples
javascriptunit-testingjestjs

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?


Solution

  • There is a solution for this now. You can use:

    jest.replaceProperty(config, 'foo', 'zed');
    

    More info: Jest Documentation - jest.replaceProperty