如何使用 Jest 检查某个元素是否可见?

问题描述 投票:0回答:2

我有一个直接的反应补偿。我想根据反应状态测试样式。比较如下所示:

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

有没有办法在不使用反应内联样式的情况下使元素不可见!?

javascript reactjs jestjs react-testing-library react-test-renderer
2个回答
8
投票

您可以从 RTL 使用

toBeVisible()
函数。 这里有文档: https://github.com/testing-library/jest-dom#tobevisible

示例:

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

0
投票

要检查元素不存在,可以使用

queryBy
来避免使用
getBy
引发错误。

使用

screen.getBy*
,您会收到“无法找到元素”错误,而使用
screen.queryBy*
,如果未找到元素,将返回“null”。

示例-

const backDrop = screen.queryByTestId('backdrop');
expect(backDrop).toBeNull();

参考 - https://testing-library.com/docs/guide-disappearance/#nottobeinthedocument

© www.soinside.com 2019 - 2024. All rights reserved.