javascript - 如何使用 Jest 检查元素是否可见?

标签 javascript reactjs jestjs react-testing-library react-test-renderer

我有一个直截了当的 react-comp。我想根据 react 状态测试样式。组合如下所示:
react 比较。

const Backdrop = ({ showBackdrop }) => {
    const backdropRef = useRef();

    function getBackdropHeight() {
        if (typeof window !== 'undefined') {
            return `calc(${document.body.clientHeight}px -
            ${backdropRef.current?.offsetTop || 0}px)`;
        }

        return 0;
    }

    return (
        <div
            data-testid="backdrop"
            className={classNames(styles.backdrop, showBackdrop ? styles.show : styles.hide)}
            ref={backdropRef}
            style={{ height: getBackdropHeight() }}
        />
    );
};
造型
.backdrop {
    width: 100%;
    position: absolute;
    left: 0;
    right: 0;
    top: 156px;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 3;
    ...
}

.show {
    opacity: 0;
    visibility: hidden;
    transition: visibility 0.25s, opacity 0.25s ease-out;
}

.hide {
    opacity: 1;
    visibility: hidden;
    transition: opacity 0.25s ease-in;
}
我总是从测试中得到的错误是,元素是可见的:
Received element is visible:
  <div class="backdrop hide" data-testid="backdrop" style="height: calc(0px -
            0px);" />

  21 |         const { getByTestId } = renderWithIntl(<Backdrop showBackdrop={false} />);
  22 | 
> 23 |         expect(getByTestId('backdrop')).not.toBeVisible();
     |                                             ^
  24 |     });
  25 | });
  26 | 
测试
it("should not render visible backdrop on falsy state", () => {
    const { getByTestId } = render(<Backdrop showBackdrop={false} />);

    expect(getByTestId('backdrop')).not.toBeVisible();
});
在不使用 react 内联样式的情况下如何使元素不可见的任何方法!?

最佳答案

您可以使用toBeVisible()来自 RTL 的功能。
在这里你有文档:
https://github.com/testing-library/jest-dom#tobevisible
例子:

// element should not be visible on screen
expect(screen.queryByText('1')).not.toBeVisible();

关于javascript - 如何使用 Jest 检查元素是否可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64026278/

相关文章:

javascript - 如何使用 GreenSock 动画平台 (GSAP) 获取比例值

javascript - 第二层侧边栏

javascript - 如何在React Native中过滤pokemon

react-native - 开 Jest 测试 __DEV__ 未定义

javascript - 如何使用 Angular JS 打开/关闭单击的 div 生成内部循环?

javascript - 使用 ...rest ES6 以奇怪的顺序放置参数

reactjs - 找不到插件 "proposal-numeric-separator"

javascript - 我的 ReactJS 代码超出了最大调用堆栈大小

javascript - 在 Electron 中运行 Jest 并使用 --inspect-brk

javascript - 尝试测试 create-react-app 项目时出现 "ReferenceError: document is not defined"