我有两个组成部分;一个页面,它使用来自子级的文件列表,并在任何文件不是有效类型时显示一条消息。
父级通过 props 将函数传递给子级,以便他们可以进行通信。
如果任何文件无效,那么我会向用户显示一条消息通知他们。
我不确定如何在 React 中使用 Jest 进行测试,因为我们正在尝试单独测试所有组件,但它们具有触发消息的回调函数依赖项。
我应该将无效的文件逻辑和消息显示移动到 child 吗?这样我会增加组件的复杂性,但更容易测试吗?
父组件
const Parent = () => {
const handleOnDocumentDrop = useCallback(
(fileList): void => {
if (invalid.length) {
// I want to be able to assert that this is shown in Jest
toast({
position: 'top-right',
title: 'title',
description: 'description',
status: 'error',
duration:'5000',
isClosable: true,
});
}
},
[]
);
return (
<Child onDocumentDrop={handleOnDocumentDrop} />
);
};
子组件const Child = ({ onDocumentDrop }) => {
const onDrop = (e) => {
e.preventDefault();
e.stopPropagation();
if (e.dataTransfer.files) {
onDocumentDrop(e.dataTransfer.files);
}
};
return (
<Flex
onDrop={onDrop}
>
</Flex>
);
};
最佳答案
const trigger = jest.fn();
const wrapper = render(<Child onDocumentDrop={trigger} />);
const images = //files to test
wrapper.find(addressTheDropzoneHere).simulate('drop', { dataTransfer: { files: images } });
expect(trigger).toBeCalledTimes(numberOfIncorrectFiles)
关于javascript - 如何在 React 中测试从子组件提升到父组件的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64417758/