首页 > 解决方案 > 向下滚动后的开玩笑测试没有找到元素

问题描述

我正在尝试模拟向下滚动。之后,isVisible 的状态应该变为 true,并且应该显示 Button 组件。

这工作正常,但我无法在测试中模拟它。

下面的主要组件

const ScrollToTop = (props: ScrollToTopProps) => {
    const {
        message = 'Back To Top',
        visibilityHeight = 300,
        containerClassName = '',
        ...restProps
    } = props;

    const [isVisible, setIsVisible] = useState(false);
    const classNames = useClassNameWithPrefixCls();

    const toggleVisibility = () => {
        if (window.pageYOffset > visibilityHeight) {
            setIsVisible(true);
        } else {
            setIsVisible(false);
        }
    };

    const scrollToTopOfPage = () => {
        window.scrollTo({
            top: 0,
            behavior: 'smooth',
        });
    };

    useEffect(() => {
        window.addEventListener('scroll', toggleVisibility);
        return () => {
            window.removeEventListener('scroll', toggleVisibility);
        };
    }, []);

    return (
        <>
            {isVisible && (
                <div
                    className={`${classNames('scroll-to-top')} ${containerClassName}`}
                    onClick={scrollToTopOfPage}
                >
                    <Button {...restProps}>{message}</Button>
                </div>
            )}
        </>
    );
};

export default ScrollToTop;

下面测试

import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import ScrollToTop from '../ScrollToTop';

describe('ScrollToTop', () => {
    test('Renders ScrollToTop with aria-label', async () => {
        render(<ScrollToTop aria-label="Go to the top" />);
        fireEvent.scroll(window, { target: { scrollY: 1000 } });
        const testy = await screen.findByLabelText('Go to the top');
        expect(testy).toBeDefined();
    });
});

下面的错误

 TestingLibraryElementError: Unable to find a label with the text of: Go to the top

    <body
      class=""
      style=""
    >
      <div />
    </body>

    <body
      class=""
      style=""
    >
      <div />
    </body>Error: Unable to find a label with the text of: Go to the top

    <body
      class=""
      style=""
    >
      <div />
    </body>

       7 |              render(<ScrollToTop aria-label="Go to the top" />);
       8 |              fireEvent.scroll(window, { target: { scrollY: 1000 } });
    >  9 |              const testy = await screen.findByLabelText('Go to the top');
         |                                         ^
      10 |              expect(testy).toBeDefined();
      11 |      });
      12 | });

如您所见,即使使用 async/await,文件也是空的。

注意: Button 是一个组件,它只呈现一个它按预期工作。我没有上传该代码,因为它可能会造成混淆。

谢谢

标签: javascriptreactjsjestjs

解决方案


推荐阅读