我在测试包装在 setTimeout 函数内的函数时遇到一些问题。 基本上,我想测试的是使用 false 参数调用 setUpdate 方法。
const UpdateContainer: FunctionComponent<UpdateProps> = ({
showUpdate,
showError,
dateOfBirth,
}) => {
const [isEditable, setIsEditable] = useState<boolean>(true);
const [isEditing, setIsEditing] = useState<boolean>(true);
const onCancel = function async() {
setIsEditable(false);
setIsEditing(false);
setTimeout(()=> {
** /*Wants to check if this method is invoked with a false param*/**
showUpdate(false);
},600);
};
const initialValues: UpdateValues = {
birth_date: dateOfBirth,
};
const formik = useFormik({
initialValues: initialValues,
});
return (
<Card
cancelText={t('cancel')}
confirmText={t('confirm')}
isEditable={isEditable}
isEditing={isEditing}
setIsEditable={setIsEditable}
setIsEditing={setIsEditing}
onCancel={() => onCancel()}
>
<CardItem
body={
<Input
disabled
id="dateOfBirthUpdate"
textTransform="none"
type="text"
value={moment(new Date(formik.values.birth_date ? formik.values.birth_date : '')).format('ll')}
/>
}
/>
</Card>
);
};
export default Card;
我尝试遵循笑话文档,但由于某种原因,测试无法检测到 setUpdate 函数的调用
这是我到目前为止所尝试过的
``
it('on Clicking Cancel inside a tool tip it sets the show update to false', async () => {
tree(props)
jest.useFakeTimers()
act(()=>{
jest.runAllTimers()
})
const cancelButton = screen.getByText('common:cancel');
expect(cancelButton).not.toBeNull();
userEvent.click(cancelButton);
const toolTipCancel= screen.getByText('common:cancelEditTooltip.cancelButtonText')
userEvent.click(toolTipCancel);
await expect(props.showUpdate).toBeCalledWith(false)
});
`
`
在测试中,在传递tree(props)中的props之前,尝试设置props.showUpdate = jest.fn()
将最后一个断言包装在 waitFor() 中,如下所示:
await waitFor(() => {
expect(props.showUpdate).toBeCalledWith(false)
})