← Back to React Course | Chapter 12: Testing React Applications | Lesson 3 of 9

Elements को Render और Query करना

Render queries 'मुझे जो चाहिए वह कहां है' पूछने के अलग तरीके जैसे हैं — कभी आप name tag से search करते हैं, कभी role से, कभी इस पर चिपके label से।
Syntax
markup
render(<Component />);

screen.getByRole("role", { name: "label" }); // throws if missing
screen.queryByText("text"); // null if missing
await screen.findByText("text"); // waits for async content

getBy vs. queryBy vs. findBy

getBy* अगर कोई matching element मौजूद न हो तो immediately एक error throw करता है, कुछ IS present यह assert करने के लिए ideal बनाते हुए। queryBy* throw करने के बजाय null return करता है, कुछ ABSENT यह assert करने के लिए सही choice बनाते हुए। findBy* एक Promise return करता है और wait करता है, उन elements के लिए ideal जो एक async action के बाद appear होते हैं।

Note:
  • एक simple mental model:
  • getBy 'यह अभी मौजूद होना चाहिए' के लिए
  • queryBy 'यह मौजूद NOT होना चाहिए' के लिए
  • findBy 'यह जल्द मौजूद होगा' के लिए।
Warning: कुछ absent है check करने के लिए getBy* उपयोग करना एक unhelpful error throw करता है एक clean assertion failure के बजाय — इसके बजाय queryBy* + toBeNull() या not.toBeInTheDocument() उपयोग करें।

उदाहरण: getBy vs. queryBy vs. findBy

markup
// Run in your local React project (npm install required)
import { render, screen } from '@testing-library/react';
import Alert from './Alert';

test('alert is not shown initially', () => {
  render(<Alert show={false} />);
  expect(screen.queryByText('Warning!')).not.toBeInTheDocument();
});

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

findBy से Async Content का Wait करना

जब content एक asynchronous action के बाद appear होता है (जैसे एक fetch resolve होना), findBy* queries एक Promise return करती हैं जो element appear होने तक या एक timeout reach होने तक repeatedly check करती है, tests में manual waiting या arbitrary setTimeout calls की ज़रूरत से बचते हुए।

Note: हमेशा एक findBy* query को await करें — await भूल जाने का मतलब है test आगे बढ़ जाता है element के actually appear होने से पहले।
Warning: findBy* का एक default timeout है (usually 1000ms) — एक genuinely slow-loading element को एक explicit longer timeout option के रूप में pass करना पड़ सकता है।

उदाहरण: Waiting for Async Content with findBy

markup
// Run in your local React project (npm install required)
import { render, screen } from '@testing-library/react';
import UserProfile from './UserProfile';

test('shows user name after loading', async () => {
  render(<UserProfile userId={1} />);
  const name = await screen.findByText('Asha');
  expect(name).toBeInTheDocument();
});

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

Recommended Query Priority

Testing Library एक priority order recommend करती है कौन सी query पहले reach करें: getByRole preferred है (यह real accessibility semantics reflect करता है), फिर form fields के लिए getByLabelText, फिर general content के लिए getByText, test-ID-based queries last resort के रूप में जब कुछ और fit न हो।

Note: इस priority order को follow करना naturally आपके components को better accessibility की तरफ push करता है, क्योंकि आप roles और labels के बारे में सोचने को forced होते हैं।
Warning: Default habit के रूप में सीधे getByTestId के लिए reach करना accessibility benefits skip करता है जो दूसरी queries encourage करती हैं, और accessibility issues miss करता है जो आपके tests otherwise reveal कर सकते थे।

उदाहरण: The Recommended Query Priority

markup
// Run in your local React project (npm install required)
// Priority order (most to least preferred):
screen.getByRole('button', { name: 'Save' });   // 1st choice
screen.getByLabelText('Email address');           // 2nd choice
screen.getByText('Welcome back');                 // 3rd choice
screen.getByTestId('save-button');                // last resort
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Role से बेहतर identify होने वाले elements के लिए getByText उपयोग करना, accessibility semantics miss करते हुए जो test otherwise verify कर सकता था।
  2. getBy, queryBy, और findBy के बीच difference न जानना — हर एक missing या async elements के लिए अलग behave करता है।
  3. container.querySelector overuse करना, Testing Library के user-centric query system को completely bypass करते हुए।
चैप्टर सारांश
  • getBy* queries अगर zero या multiple matches मिलें तो throw करती हैं — उन elements के लिए उपयोग करें जो अभी मौजूद होने की उम्मीद है।
  • queryBy* throw करने के बजाय null return करती है — यह assert करने के लिए उपयोग करें कि कुछ मौजूद NOT है।
  • findBy* एक Promise return करती है, एक element appear होने का wait करते हुए — उस content के लिए उपयोग करें जो asynchronously दिखता है।
  • Query priority (recommended order): getByRole, getByLabelText, getByText, फिर ज़्यादा implementation-specific options।
ब्राउज़र सपोर्ट

npm install @testing-library/react चाहिए — एक Node test environment में run होता है, इस browser sandbox में नहीं।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.