所以我有一些问题,请帮忙:)
这是我要测试的组件-
export const Error = ({ message }) => {
const [open, setOpen] = React.useState(true);
function handleClose() {
setOpen(false);
}
return (
<Snackbar
data-testid="error-component"
anchorOrigin={{
vertical: 'top',
horizontal: 'center',
}}
open={open}
autoHideDuration={6000}
>
<Alert elevation={6} variant="filled" onClose={handleClose} severity="error" action={
<IconButton
aria-label="close"
color="inherit"
size="small"
onClick={handleClose}
data-testid="error-close-button"
>
<CloseIcon fontSize="inherit" />
</IconButton>
}>
{message}
</Alert>
</Snackbar>
);
};
这是我的测试-
it('render without crash', () => {
const div = document.createElement('div');
ReactDOM.render(<Error></Error>, div);
});
it('render error component correctly', () => {
const { queryByTestId } = render(<Error />);
expect(queryByTestId('error-component')).toBeTruthy();
});
it('error close button click fired', () => {
const onClickMock = jest.fn();
const { queryByTestId } = render(<Error />);
fireEvent.click(queryByTestId('error-close-button'));
expect(onClickMock).toHaveBeenCalledTimes(1);
expect(onClickMock).toHaveBeenCalled();
});
我收到此错误-
Error: expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
答案 0 :(得分:0)
正如我们的阿姆斯特丹代表所说,我认为最好是确保error-close-button
从屏幕上消失而不是调用onClick。
我认为此确认是对onClick被调用的保证。
it("error close button click fired", async () => {
render(<Error message="error" />);
expect(screen.queryByTestId('error-close-button')).toBeTruthy();
fireEvent.click(screen.getByTestId('error-close-button'));
await waitFor(() =>
expect(screen.queryByTestId('error-close-button')).toBeFalsy();
)
});