How can I mock Lodash's - get method to return a specific value?
I have the following function in my code.
Code
import React, { Fragment } from 'react';
import get from 'lodash/get';
import MyComponent from '../../MyComponent';
const A = () => {
// this path is fine, tested working in browser.
const getData = () => get(window.getStatus(),
'data.toJS()[\'base-path\'].current[\'frame-name\'].exclusions[\'period\']');
return (
<div>
{ getData() === 'customValue' ? <Fragment/> : <MyComponent/> }
</div>
);
};
export default A;
I am trying to test this by mocking the return value so that I can get correct customValue.
But when I mock it as follows in my test. It doesn't work. The value is just undefined.
Test
import get from 'lodash/get';
jest.mock('lodash/get');
global.getState = jest.fn(() => 'mock state');
describe('Test', () => {
const render = (props) => shallow(
<A
{...props}
/>
);
it('should fail', () => {
get.mockReturnValueOnce('customValue');
const r = render({
someKey: 'someValue',
});
expect(r.find('MyComponent')).toBeTruthy();
});
}
This test ends up passing which is incorrect. I passed in customValue as the mock value.
This test should have rendered Fragment (instead of MyComponent) due to this and failed.
Please advice how I could achieve this pls.