gpt4 book ai didi

reactjs - 如何使用 Jest 和 Enzyme 测试 ui-material TextField 的 onChange

转载 作者:行者123 更新时间:2023-12-04 09:13:26 24 4
gpt4 key购买 nike

我是测试新手,我不知道如何测试 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

最佳答案

首先,您必须监视onChange功能:

const onChange = jest.spyOn(TextField.prototype, 'onChange');
@material-ui提供复杂的组件,所以我猜你会像这样测试它(还要注意 enzyme 的 find() 返回节点的集合):
wrapper.find(TextField).find('input').at(0).simulate('change', event);

关于reactjs - 如何使用 Jest 和 Enzyme 测试 ui-material TextField 的 onChange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63310588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com