Mock a Lodash method to return a specific value

Viewed 496

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.

1 Answers

Here's one way to do it:

// getData.js
import get from 'lodash/get';


export const getData = () => get(window.getStatus(),
    'data.toJS()[\'base-path\'].current[\'frame-name\'].exclusions[\'period\']');
import React, { Fragment } from 'react';
import { getData } from './getData';
import MyComponent from '../../MyComponent';

const A = () => {

  return (
    <div>
      { getData() === 'customValue' ? <Fragment/> : <MyComponent/> } 
    </div>
  );
};

export default A;

Now you can mock the getData function exported by getData that A uses.

An alternative idea is to mock window.getStatus(). The reason why I suggest extracting and mocking getData is because it doesn't need to belong inside A, anyway.

Don't mock lodash, that's just silly.

Related