测试库:使用 waitForElementToBeRemove 删除元素不会获得开玩笑的覆盖率



这里有一个Toast组件,当单击按钮时会显示,并在x秒后消失。对于测试,当API调用成功时,waitFor用于将showToast状态更改为true,然后waitForElementToBeRemoved用于检查toast组件是否已从屏幕中删除。

测试正在通过,因此假设showToast变为false。但是,当我检查jest覆盖率时,hide={() => setShowToast(false)}行仍然显示为未覆盖。

使用testing-library覆盖该线路需要什么?

Toast组件:

const Toast = props => {
const { message, color, iconName, show, hide, background, timeoutDuration, ...rest } = props;
useEffect(() => {
if (show) {
const timeout = setTimeout(() => {
hide();
}, timeoutDuration * 1000 + 1000);
return () => clearTimeout(timeout);
}
}, [show, timeoutDuration]);
return (
<Box>
<Container {...rest} show={show} timeoutDuration={timeoutDuration}>
<StyledToast py={1} px={2} background={background} bgColor={colors[color]} role="alert">
<StyledIcon name={iconName} color={color} />
<StyledP color={color} fontSize={[14, 16]}>
{message}
</StyledP>
</StyledToast>
</Container>
</Box>
);
};

使用Toast的组件:

const [showToast, setShowToast] = useState(false);
{showToast && (
<Toast
message="Store Settings successfully updated!"
color="green"
iconName="check-circle"
background={true}
show={showToast}
timeoutDuration={10}
zIndex={10}
hide={() => setShowToast(false)}
/>
)}

测试:

import '@testing-library/jest-dom';
import { render, screen, fireEvent, waitFor, waitForElementToBeRemoved } from '@testing-library/preact';

test('Clicking OK displays Toast and it disappears', async () => {
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ data: {}] } })
})
);

const CheckBox = screen.getByTestId('some-id');
fireEvent.click(CheckBox);
const SaveButton = screen.getByText('Save');
fireEvent.click(SaveButton);
expect(screen.getByText('OK')).toBeTruthy();
const OKButton = screen.getByText('OK');
fireEvent.click(OKButton);

await waitFor(() => {
expect(screen.getByText('Store Settings successfully updated!')).toBeInTheDocument();
}, { timeout: 11000 });

waitForElementToBeRemoved(screen.getByText('Store Settings successfully updated!')).then(() =>
expect(screen.queryByText('Store Settings successfully updated!')).not.toBeInTheDocument()
);

});

尝试

await waitForElementToBeRemoved(...)

由于waitForElementToBeRemoved是一个异步函数调用

相关内容

  • 没有找到相关文章

最新更新