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

查看:30
本文介绍了你如何使用 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 测试 jest 中不存在的东西?

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天全站免登陆