我如何模拟 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/