您如何使用Jest和react-testing-library测试元素的不存在? [英] How do you test for the non-existence of an element using jest and react-testing-library?

查看:383
本文介绍了您如何使用Jest和react-testing-library测试元素的不存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件库,正在编写有关使用Jest和react-testing-library的单元测试.基于某些道具或事件,我想验证是否未渲染某些元素.

I have a component library that I'm writing unit tests for using Jest and react-testing-library. Based on certain props or events I want to verify that certain elements aren't being rendered.

getByTextgetByTestId等在react-testing-library中抛出并出错,导致在expect函数触发之前测试失败.

getByText, getByTestId, etc throw and error in react-testing-library if the element isn't found causing the test to fail before the expect function fires.

您如何使用react-testing-library来测试玩笑中不存在的东西?

How do you test for something not existing in jest using react-testing-library?

推荐答案

来自 DOM Testing-library Docs -外观和消失

不存在断言元素

标准的getBy方法在找不到元素时抛出错误,因此 如果您要断言DOM中不存在某个元素, 您可以改用queryBy API:

Asserting elements are not present

The standard getBy methods throw an error when they can't find an element, so if you want to make an assertion that an element is not present in the DOM, you can use queryBy APIs instead:

const submitButton = screen.queryByText('submit')
expect(submitButton).toBeNull() // it doesn't exist

queryAll API版本返回匹配节点的数组.的长度 在添加元素或从元素中删除元素后,数组对于断言很有用. DOM.

The queryAll APIs version return an array of matching nodes. The length of the array can be useful for assertions after elements are added or removed from the DOM.

const submitButtons = screen.queryAllByText('submit')
expect(submitButtons).toHaveLength(2) // expect 2 elements

not.toBeInTheDocument

jest-dom实用程序库提供了 .toBeInTheDocument()匹配器,可用于断言元素是 是否在文档正文中.这比断言更有意义 查询结果为null.

not.toBeInTheDocument

The jest-dom utility library provides the .toBeInTheDocument() matcher, which can be used to assert that an element is in the body of the document, or not. This can be more meaningful than asserting a query result is null.

import '@testing-library/jest-dom/extend-expect'
// use `queryBy` to avoid throwing an error with `getBy`
const submitButton = screen.queryByText('submit')
expect(submitButton).not.toBeInTheDocument()

这篇关于您如何使用Jest和react-testing-library测试元素的不存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆