Code Script 🚀

How do you test for the non-existence of an element using jest and react-testing-library

February 15, 2025

How do you test for the non-existence of an element using jest and react-testing-library

Investigating is a captious facet of package improvement, particularly successful the dynamic planet of Respond purposes. Making certain that your parts behave arsenic anticipated, some once parts are immediate and notably absent, is important for a sturdy person education. This station dives into the specifics of investigating for the non-beingness of parts successful your Respond initiatives utilizing Jest and Respond Investigating Room, 2 almighty instruments that advance champion practices successful investigating UI parts. Mastering these methods volition not lone better the stableness of your exertion however besides pb to much maintainable and assured codification.

Wherefore Trial for Non-Beingness?

Investigating for the lack of components is arsenic crucial arsenic verifying their beingness. It ensures that parts are conditionally rendered appropriately, stopping sudden behaviour and UI glitches. Ideate a loading spinner that stays connected the surface equal last information has loaded. This not lone seems to be unprofessional however tin besides confuse customers. Investigating for non-beingness helps drawback these points aboriginal.

Moreover, it helps forestall regressions. Arsenic your codebase evolves, seemingly innocuous adjustments tin inadvertently impact component visibility. These assessments enactment arsenic a condition nett, alerting you to unintended penalties and safeguarding towards breaking present performance. By persistently verifying that components are not rendered once they shouldn’t beryllium, you make a much predictable and dependable person education.

This thorough investigating attack enhances person education, catches regressions aboriginal, and contributes to the instauration of a unchangeable and dependable exertion.

Utilizing queryBy Queries

Respond Investigating Room presents a almighty fit of queries particularly designed to grip the script of component lack. The queryBy queries instrument the component if it’s recovered, and null other. This makes them absolutely suited for asserting non-beingness. Dissimilar getBy queries, which propulsion an mistake if the component isn’t recovered, queryBy gives a much elegant attack once you anticipate an component to beryllium absent.

For case, if you privation to trial that an mistake communication is not displayed once a signifier is legitimate, you might usage queryByText to hunt for the mistake communication. Successful your trial assertion, you would past cheque if the consequence of the question is null. This confirms that the mistake communication is accurately hidden once the signifier is legitimate.

Examples of queryBy queries see queryByText, queryByRole, and queryByTestId. Selecting the correct question aligns with accessibility champion practices, making your assessments much strong and person-centered.

Leveraging waitForElementToBeRemoved

Typically, components are eliminated asynchronously. For illustration, an component mightiness vanish last an API call completes oregon a person action. Successful specified circumstances, utilizing waitForElementToBeRemoved from Respond Investigating Room is important. This relation waits for an component to beryllium eliminated from the DOM, offering a cleanable manner to grip asynchronous behaviour successful your checks.

Fto’s opportunity you person a notification banner that fades retired last a fewer seconds. You tin usage waitForElementToBeRemoved to guarantee the banner is accurately eliminated last the timeout. This prevents flaky checks and ensures that your UI behaves arsenic meant successful dynamic eventualities.

This relation is particularly utile once dealing with animations and transitions, guaranteeing your checks decently relationship for the timing of component elimination.

Champion Practices for Investigating Non-Beingness

To maximize the effectiveness of your checks, see these champion practices:

  • Prioritize person-centric queries: Direction connected however customers work together with your exertion. Usage queries similar queryByRole to indicate person action patterns.
  • Debar investigating implementation particulars: Trial what the person sees and interacts with, not however the constituent is carried out internally. This makes your assessments much resilient to codification adjustments.

By adhering to these practices, you make much maintainable and dependable assessments that lend to a amended person education. Adhering to these practices ensures your assessments are person-targeted, resistant to codification modifications, and lend to a amended person education.

Illustration: Investigating a Conditional Mistake Communication

See a elemental signifier with a required tract. An mistake communication ought to look lone if the tract is near bare. Present’s however you mightiness trial this utilizing Jest and Respond Investigating Room:

import { render, surface, fireEvent } from '@investigating-room/respond'; import Signifier from './Signifier'; trial('mistake communication seems once tract is bare', async () => { render(<Signifier />); fireEvent.subject(surface.getByRole('fastener', { sanction: /subject/i })); anticipate(await surface.findByText(/tract is required/i)).toBeInTheDocument(); }); trial('mistake communication disappears once tract is crammed', async () => { render(<Signifier />); fireEvent.alteration(surface.getByLabelText(/sanction/i), { mark: { worth: 'John' } }); fireEvent.subject(surface.getByRole('fastener', { sanction: /subject/i })); anticipate(surface.queryByText(/tract is required/i)).toBeNull(); }); 

This illustration demonstrates however to trial some the beingness and lack of the mistake communication, guaranteeing the signifier behaves accurately nether antithetic situations.

Larn much astir investigating Respond purposes.Infographic Placeholder: Ocular cooperation of utilizing queryBy and waitForElementToBeRemoved.

FAQ

Q: What’s the quality betwixt getBy and queryBy?

A: getBy throws an mistake if the component is not recovered, piece queryBy returns null. Usage queryBy once you anticipate an component to beryllium possibly absent.

Investigating for the non-beingness of components utilizing Jest and Respond Investigating Room is indispensable for gathering sturdy and dependable Respond functions. By using the methods mentioned—utilizing queryBy queries, leveraging waitForElementToBeRemoved, and adhering to champion practices—you tin guarantee your parts behave arsenic anticipated nether assorted circumstances, starring to a amended person education. Commencement incorporating these strategies into your investigating workflow present for much unchangeable and maintainable codification.

Research further sources connected investigating Respond functions with Jest and Respond Investigating Room to additional refine your abilities. This proactive attack to investigating volition undoubtedly heighten the choice and reliability of your initiatives.

Question & Answer :
I person a constituent room that I’m penning part exams for utilizing Jest and respond-investigating-room. Primarily based connected definite props oregon occasions I privation to confirm that definite parts aren’t being rendered.

getByText, getByTestId, and many others propulsion and mistake successful respond-investigating-room if the component isn’t recovered inflicting the trial to neglect earlier the anticipate relation fires.

However bash you trial for thing not present successful jest utilizing respond-investigating-room?

From DOM Investigating-room Docs - Quality and Disappearance

Asserting components are not immediate

The modular getBy strategies propulsion an mistake once they tin’t discovery an component, truthful if you privation to brand an assertion that an component is not immediate successful the DOM, you tin usage queryBy APIs alternatively:

const submitButton = surface.queryByText('subject') anticipate(submitButton).toBeNull() // it doesn't be 

The queryAll APIs interpretation instrument an array of matching nodes. The dimension of the array tin beryllium utile for assertions last parts are added oregon eliminated from the DOM.

const submitButtons = surface.queryAllByText('subject') anticipate(submitButtons).toHaveLength(2) // anticipate 2 parts 

not.toBeInTheDocument

The jest-dom inferior room offers the .toBeInTheDocument() matcher, which tin beryllium utilized to asseverate that an component is successful the assemblage of the papers, oregon not. This tin beryllium much significant than asserting a question consequence is null.

import '@investigating-room/jest-dom/widen-anticipate' // usage `queryBy` to debar throwing an mistake with `getBy` const submitButton = surface.queryByText('subject') anticipate(submitButton).not.toBeInTheDocument()