【问题标题】:Mock a Lodash method to return a specific value模拟 Lodash 方法以返回特定值
【发布时间】:2021-10-03 22:10:01
【问题描述】:

如何模拟Lodash's - get 方法以返回特定值?

我的代码中有以下函数。

代码

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;

我正在尝试通过模拟返回值来测试这一点,以便我可以得到正确的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)并且失败了。

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

【问题讨论】:

    标签: javascript jestjs lodash


    【解决方案1】:

    这是一种方法:

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

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

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

    不要嘲笑lodash,那太傻了

    【讨论】:

      猜你喜欢
      • 2018-12-25
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      • 2022-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多