开玩笑:预计 getByRole 元素会丢失,但测试失败并出现 TestLibraryElementError

Pau*_*a T 6 unit-testing reactjs jestjs

我有一个测试,用于getByRole验证页面中是否存在元素。但是,我还有另一个测试,我预计该元素会丢失。我认为使用语法这会非常简单.not,但是当我尝试时出现错误。

我尝试过的事情:

expect(getByRole('timestamp')).not.toBeInTheDocument();
expect(getByRole('timestamp')).toBeNull;
expect(getByRole('timestamp')).toThrowError();
... and more...
Run Code Online (Sandbox Code Playgroud)

我得到的错误:

TestingLibraryElementError: Unable to find an accessible element with the role "timestamp"
Run Code Online (Sandbox Code Playgroud)

如何验证文档中不存在具有给定角色的元素?

Pau*_*a T 4

感谢这篇博文,我发现您可以使用queryByRole而不是getByRole测试您期望元素丢失的情况。

最终版本如下所示:

expect(queryByRole('timestamp')).not.toBeInTheDocument();
Run Code Online (Sandbox Code Playgroud)