将 Lodash 方法模拟为 return 特定值

Mock a Lodash method to return a specific value

如何将 Lodash's - get 方法模拟为 return 特定值?

我的代码中有以下函数。

代码

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;

我正在尝试通过模拟 return 值来测试它,以便我可以获得正确的 customValue.

但是当我在测试中如下模拟它时。它不起作用。该值未定义。

测试

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();
  });
}

这个测试最终通过了,这是不正确的。我传入了 customValue 作为模拟值。

此测试本应渲染 Fragment(而不是 MyComponent),但失败了。

请告诉我如何实现这一点。

这是一种方法:

// 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;

现在您可以模拟 A 使用的 getData 导出的 getData 函数。

另一种想法是模拟 window.getStatus()。我建议提取和模拟 getData 的原因是因为它不需要属于 A,无论如何。

不要嘲笑lodash,那是愚蠢的