使用Jest和酶类,我如何模拟一个子组件的回调函数来返回一个特定的值,然后在父组件的其他地方测试它的效果?
在下面的示例中,当Child回调onSelectionChange发生时,它会更改状态,从而启用以前通过在道具<Button disabled={disableButton} />中传递状态值而禁用的状态。
我想要模拟子组件,从onSelectionChange返回false,并测试按钮禁用的道具是否已经更改。
import React, { useState } from "react";
import Button from "./Button";
import Child from "./Child";
const Parent = () => {
const [disableButton, setDisableButton] = useState(true);
return (
<>
<Button disabled={disableButton} />
<Child onSelectionChange={(isDisabled) => setDisableButton(isDisabled)} />
</>
);
};
export default Parent;发布于 2022-04-06 02:34:55
您不需要模拟任何组件。您可以使用.invoke(invokePropName)(...args) => Any API调用函数支柱。您甚至不必关心如何触发onSelectionChange。只要用正确的参数调用它,就需要确保这一点。
例如。
Parent.tsx
import React, { useState } from 'react';
import Button from './Button';
import Child from './Child';
const Parent = () => {
const [disableButton, setDisableButton] = useState(true);
return (
<>
<Button disabled={disableButton} />
<Child onSelectionChange={(isDisabled) => setDisableButton(isDisabled)} />
</>
);
};
export default Parent;Child.tsx
import React from 'react';
const Child = ({ onSelectionChange }) => {
return <div>Child</div>;
};
export default Child;Button.tsx
import React from 'react';
const Button = (props) => {
return <button {...props}>click me</button>;
};Parent.test.tsx
import { shallow } from 'enzyme';
import React from 'react';
import Button from './Button';
import Child from './Child';
import Parent from './parent';
describe('71713192', () => {
test('should pass', () => {
const wrapper = shallow(<Parent />);
expect(wrapper.find(Button).exists()).toBeTruthy();
expect(wrapper.find(Button).prop('disabled')).toBeTruthy();
wrapper.find(Child).invoke('onSelectionChange')(false);
expect(wrapper.find(Button).prop('disabled')).toBeFalsy();
});
});测试结果:
PASS stackoverflow/71713192/parent.test.tsx (9.794 s)
71713192
✓ should pass (26 ms)
------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------|---------|----------|---------|---------|-------------------
All files | 87.5 | 100 | 50 | 87.5 |
Button.tsx | 75 | 100 | 0 | 75 | 4
Child.tsx | 75 | 100 | 0 | 75 | 4
parent.tsx | 100 | 100 | 100 | 100 |
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.596 s, estimated 12 s包版本:
"enzyme": "^3.11.0",
"react": "^16.14.0",
"jest": "^26.6.3"https://stackoverflow.com/questions/71713192
复制相似问题