测试库:使用waitForElementToBeRemoved移除元素不会取得jest涵盖范围

lf5gs5x2  于 2022-12-08  发布在  Jest
关注(0)|答案(1)|浏览(163)

下面是一个吐司组件,当点击按钮时会显示该组件,x秒后会消失。为了测试,当API调用成功时,waitFor用于将showToast状态更改为true,然后waitForElementToBeRemoved用于检查Toast组件是否已从屏幕中删除。
测试通过了,所以假设showToast变成了false。但是当我检查jest覆盖率时,hide={() => setShowToast(false)}这行仍然显示为未覆盖。
使用testing-library覆盖该线需要什么?
吐司元件:

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>
  );
};

使用吐司的组件:

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()
        );
        
      });
sy5wg1nm

sy5wg1nm1#

尝试

await waitForElementToBeRemoved(...)

因为waitForElementToBeRemoved是异步函数调用

相关问题