javascript - 模拟 Lodash 方法以返回特定值

标签 javascript jestjs lodash

我如何模拟 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)并且失败了。
请建议我如何实现这一点。

最佳答案

这是一种方法:

// 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 , 反正。
不要 mock lodash ,这太傻了 .

关于javascript - 模拟 Lodash 方法以返回特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69429263/

相关文章:

javascript - 使用 nockjs 和 jest 对 promise /异步单元测试的代码覆盖问题

reactjs - 我如何使用 Jest 和 React 测试库来测试它?

javascript - 相当于 JavaScript 中 Lodash 的 .maxBy

javascript - 使用 MySQL 查询或 javascript 优化数据

javascript - JS 秒表/倒数计时器 : Seconds Changing to 3 Digits

javascript - NodeJS 如果字符串包含执行脚本

javascript - 有人可以告诉我在哪里可以很好地了解 Javascript 中的 Dot Notation

javascript - Jest 会吞下 console.log 语句吗?有办法改变这个吗?

javascript - 查明函数是匿名的还是在对象中定义的

javascript - LoDash/Underscorejs 不是全局变量