Jest mock an object

2019-07-21 04:55发布

问题:

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?

回答1:

Its just a mock that returns the object instead of a function

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

or

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

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