【问题标题】:How can I check whether an element is visible with Jest?如何使用 Jest 检查元素是否可见?
【发布时间】:2023-03-04 12:19:02
【问题描述】:

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

反应比较。

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 内联样式的情况下如何让元素不可见!?

【问题讨论】:

  • 你可以试试toHaveStyle()断言,传递'visibility: hidden'作为参数
  • 不行……接收到的值也是visible
  • 嗨。期望来自样式表的 css 样式在运行时在 jest/jsdom 测试环境中被识别存在一个不直截了当的问题。请参阅我曾经在 jest-dom 问题中留下的评论:github.com/testing-library/jest-dom/issues/…

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


【解决方案1】:

您可以使用 RTL 中的 toBeVisible() 函数。 在这里你有文档: https://github.com/testing-library/jest-dom#tobevisible

例子:

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

【讨论】:

    猜你喜欢
    • 2017-01-01
    • 2011-02-08
    • 2012-07-08
    • 1970-01-01
    • 2021-02-19
    • 2014-04-22
    • 2020-08-06
    • 2014-08-09
    相关资源
    最近更新 更多