【发布时间】:2026-02-13 16:00:01
【问题描述】:
我是测试新手,我不知道如何测试 TextField 组件中的变化值
export const ParentComponent = ({
question,
onValueChange
}: ParentProps) => {
const [value, setValue] = useState(default);
const onChange = event => {
const answer = event.target.value;
setValue(answer);
clearTimeout(timeout);
timeout = setTimeout(() => {
onValueChange(question);
}, 500);
};
return (
<TextField
className={classes.textField}
InputLabelProps={{
className: classes.color
}}
onChange={onChange}
value={value || ""}
/>);
};
这是我到目前为止阅读的其他答案的内容,不确定如何处理 onValueChange 和 onChange 之间的区别:
describe("ParentComponent", () => {
let mount;
beforeEach(() => {
mount = createMount();
});
afterEach(() => {
mount.cleanUp();
});
it("renders", () => {
const wrapper = mount(<ParentComponent question={Question} onValueChange={() => {}} />);
expect(wrapper).not.toBeNull();
});
it("Should change value when text is entered", () => {
const onChange = jest.fn();
const wrapper = mount(<ParentComponent question={Question} onValueChange={() => {}} />);
const event = {
target: {
value: "This is just for test"
}
};
wrapper.find(TextField).simulate("change", event);
expect(onChange).toHaveBeenCalled();
expect(onChange).toHaveBeenCalledWith("This is just for test");
});
收到此错误:
Error: expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
【问题讨论】:
标签: reactjs unit-testing jestjs material-ui enzyme