【发布时间】: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