Testing UI the way users use it
How to test components the way people use them: Testing Library's guiding principle and query priority, getBy, queryBy and findBy, user-event instead of fireEvent, jest-dom assertions on what users perceive, a form example, what jsdom cannot show, and tests that break for the wrong reasons.
Reading level
Shows sections up to the selected level.
This topic starts at Junior level.
Test what the user sees and does
Testing Library müəllifi Kent C. Dodds-un bir cümləsi üzərində qurulub: "Testlər proqramın necə istifadə olunduğuna nə qədər çox bənzəsə, sənə bir o qədər çox əminlik verə bilər." Komponentin iki növ istifadəçisi var: onu görüb klikləyən insan və onu props ilə render edən developer. UI testi komponentlə məhz onlar kimi davranmalıdır: elementləri ekranda göstərdiklərinə görə tapmalı, insan kimi qarşılıqlı əlaqəyə girməli və sonda ekranda nə olduğunu yoxlamalıdır.
Qalan hər şeyi (state dəyişənlərini, hook-ları, komponent instance-larını, CSS class adlarını) Kent C. Dodds implementasiya detalları adlandırır: "kodunun istifadəçilərinin adətən işlətmədiyi, görmədiyi, hətta varlığından xəbər tutmadığı şeylər". Onlara söykənən testlər hər iki istiqamətdə yanılır. Refaktorinq zamanı, məsələn, useState useReducer-ə çevriləndə, istifadəçi üçün heç nə dəyişməsə də düşürlər. Ekrandakı düymə artıq heç nə etməyəndə isə keçməyə davam edirlər.
İlk komponent testi
React üçün geniş yayılmış alət dəsti belədir: Vitest testləri simulyasiya olunmuş brauzer mühitində (jsdom və ya happy-dom) işə salır, React Testing Library komponenti render edir, @testing-library/user-event istifadəçinin rolunu oynayır, @testing-library/jest-dom isə DOM üçün matcher-lər əlavə edir.
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { expect, test } from "vitest";
import { QuantityPicker } from "./QuantityPicker";
test("increases the quantity", async () => {
const user = userEvent.setup();
render(<QuantityPicker initial={1} />);
await user.click(screen.getByRole("button", { name: "Increase quantity" }));
expect(screen.getByText("Quantity: 2")).toBeInTheDocument();
});renderkomponentidocument.body-yə əlavə etdiyidiv-in içinə mount edir.screendocument.body-yə bağlanmış bütün query-ləri saxlayır. Testing Libraryrender-in qaytardığı query-lər əvəzinə ondan istifadəni tövsiyə edir.- Test əl ilə yoxlama kimi oxunur: düyməni rolu və adı ilə tap, kliklə, yeni mətni axtar. Test sayın
useState-də, reducer-də, yoxsa store-da saxlandığını bilmir.
Kent C. Dodds-un təsnifatında bir komponentin belə testi unit testdir. Eyni alətlər şəbəkəsi mock edilmiş bütöv səhifələri də render edir, o isə bunları sayır. Hər iki halda test real brauzerdə yox, simulyasiya olunmuş brauzerdə işləyir.
Asanlıqla gözdən qaçan quraşdırma
Hər testdən sonra cleanup render-in mount etdiyini unmount edir. React Testing Library onu yalnız test runner qlobal afterEach təqdim edəndə avtomatik qeydiyyatdan keçirir. Vitest isə default olaraq bunu etmir, ona görə ya globals: true təyin et, ya da setup faylında afterEach içində cleanup() çağır. Həmin setup faylı @testing-library/jest-dom/vitest-i də import edir: o, Vitest-in expect-inə toBeInTheDocument kimi matcher-lər əlavə edir. Cleanup olmasa, əvvəlki testin DOM-u sənəddə qalır və növbəti test hər şeydən iki dənə tapır.
Testing Library is built around one sentence by its author, Kent C. Dodds: "The more your tests resemble the way your software is used, the more confidence they can give you." A component has two kinds of users: the person who sees and clicks it, and the developer who renders it with props. A UI test should deal with the component the way they do: find elements by what they show, interact the way a person would, and check what ends up on the screen.
Everything else (state variables, hooks, component instances, CSS class names) is what Kent C. Dodds calls implementation details: "things which users of your code will not typically use, see, or even know about." Tests built on them fail in both directions. They break when you refactor, for example when useState becomes useReducer, although nothing changed for the user. And they keep passing when the button on the screen no longer does anything.
A first component test
A common stack for React: Vitest runs the tests in a simulated browser environment (jsdom or happy-dom), React Testing Library renders the component, @testing-library/user-event plays the user, and @testing-library/jest-dom adds matchers for the DOM.
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { expect, test } from "vitest";
import { QuantityPicker } from "./QuantityPicker";
test("increases the quantity", async () => {
const user = userEvent.setup();
render(<QuantityPicker initial={1} />);
await user.click(screen.getByRole("button", { name: "Increase quantity" }));
expect(screen.getByText("Quantity: 2")).toBeInTheDocument();
});rendermounts the component into adivthat it appends todocument.body.screenholds every query, bound todocument.body. Testing Library recommends it over the queries thatrenderreturns.- The test reads like a manual check: find the button by its role and name, click it, look for the new text. It does not know whether the count lives in
useState, a reducer or a store.
In Kent C. Dodds' classification, a test of one component like this is a unit test. The same tools also render whole pages with the network mocked, which he counts as . Either way, the test runs in a simulated browser, not a real one.
Setup that is easy to miss
After each test, cleanup unmounts what render mounted. React Testing Library registers it automatically only when the test runner provides a global afterEach. Vitest does not by default, so either set globals: true or call cleanup() in an afterEach in a setup file. The same setup file imports @testing-library/jest-dom/vitest, which adds matchers such as toBeInTheDocument to Vitest's expect. Without cleanup, the previous test's DOM stays in the document, and the next test finds two of everything.
Finding elements: the query priority
Testing Library-nin query-ləri elementləri insanlar kimi tapır. Onun sənədləri bu sıranı tövsiyə edir:
- Hamı üçün əlçatan query-lər.
getByRole("demək olar ki, hər şey üçün əsas seçimin"), form sahələri üçüngetByLabelText, sahənin bundan yaxşı heç nəyi olmayandagetByPlaceholderText, interaktiv olmayan məzmun üçüngetByText, doldurulmuş sahələr üçüngetByDisplayValue. - Semantik query-lər.
getByAltTextvəgetByTitle. Sənədlər xəbərdarlıq edir ki,title-ı screen reader-lər ardıcıl oxumur, görən istifadəçilər üçün isə o, default olaraq görünmür. - Test ID-lər.
getByTestId, yalnız başqa heç nə uyğun gəlməyəndə: istifadəçilərdata-testid-i nə görür, nə də eşidir.
screen.getByRole("heading", { name: "Order summary" });
screen.getByRole("button", { name: /place order/i });
screen.getByRole("checkbox", { name: "Gift wrap" });
screen.getByLabelText("Promo code");
screen.getByText("Free delivery on orders over $50");Role query-lər niyə həm də əlçatanlığı yoxlayır
getByRole(role, { name }) accessibility tree-də, yəni screen reader-in istifadə etdiyi eyni məlumatda axtarır. Rol elementin özündən gəlir (<button> heç bir role atributu olmadan düymədir), ad isə onun : düymənin mətni, sahənin label-i, aria-label. getByRole("button", { name: "Close" }) yalnız ikondan ibarət bağlama düyməsini tapa bilmirsə, screen reader istifadəçisi də adsız "button" eşidir, deməli, test real bug tapıb. Role query düşəndə xəta mesajı tapdığı əlçatan rolları və adları sadalayır; problemi görmək üçün çox vaxt bu kifayətdir. Brauzerlərin adı necə hesabladığı ARIA və fokus mövzusunda izah olunur.
Bilməli olduğun bir istisna: <input type="password">-in implicit rolu yoxdur, ona görə onu getByLabelText ilə tap.
Mətnə görə axtarış
Sətir kənar boşluqlar silinib daxili boşluqlar birləşdirildikdən sonra bütün mətnlə, böyük-kiçik hərfə həssas şəkildə müqayisə olunur. Regular expression isə mətnin bir hissəsinə uyğun gəlir: "Place order" "Place order now"-a çevriləndə də /place order/i onu tapır. { exact: false } böyük-kiçik hərfə həssas olmayan alt sətir axtarışı verir, amma sənədlər qeyri-dəqiq axtarış üçün regex-ə üstünlük verir. getByText yalnız elementin öz mətn node-larını müqayisə edir, ona görə <p>Total: <strong>$40</strong></p> "Total: $40"-a uyğun gəlmir. Bunun əvəzinə rolu və adı olan elementi tap və ya paraqrafın mətnini toHaveTextContent ilə yoxla.
Səhifənin bir hissəsində axtarmaq üçün query-ləri within ilə məhdudlaşdır:
const cart = screen.getByRole("list", { name: "Cart" });
expect(within(cart).getAllByRole("listitem")).toHaveLength(2);Testing Library's queries find elements the way people do. Its docs recommend this order:
- Queries accessible to everyone.
getByRole("your top preference for just about everything"),getByLabelTextfor form fields,getByPlaceholderTextwhen a field has nothing better,getByTextfor non-interactive content,getByDisplayValuefor filled-in fields. - Semantic queries.
getByAltTextandgetByTitle. The docs warn thattitleis not read consistently by screen readers and is not visible to sighted users by default. - Test IDs.
getByTestId, only when nothing else fits: users can neither see nor hear adata-testid.
screen.getByRole("heading", { name: "Order summary" });
screen.getByRole("button", { name: /place order/i });
screen.getByRole("checkbox", { name: "Gift wrap" });
screen.getByLabelText("Promo code");
screen.getByText("Free delivery on orders over $50");Why role queries also test accessibility
getByRole(role, { name }) searches the accessibility tree, the same information a screen reader uses. The role comes from the element (<button> is a button without any role attribute), and the name is its : a button's text, a field's label, an aria-label. If getByRole("button", { name: "Close" }) cannot find an icon-only close button, a screen reader user hears an unnamed "button" too, and the test has found a real bug. When a role query fails, the error lists the accessible roles and names that it did find, which is often enough to see the problem. How browsers compute names is covered in the topic on ARIA and focus.
One exception to know: <input type="password"> has no implicit role, so find it with getByLabelText.
Matching text
A string matches the whole text, case-sensitively, after trimming and collapsing whitespace. A regular expression matches part of it: /place order/i survives "Place order" becoming "Place order now". { exact: false } gives a case-insensitive substring match, but the docs prefer a regex for fuzzy matching. getByText compares only an element's own text nodes, so <p>Total: <strong>$40</strong></p> does not match "Total: $40". Query an element that has a role and name instead, or check the paragraph's text with toHaveTextContent.
To search inside one part of the page, scope the queries with within:
const cart = screen.getByRole("list", { name: "Cart" });
expect(within(cart).getAllByRole("listitem")).toHaveLength(2);getBy, queryBy and findBy
Hər query üç formada olur və prefiks element olmayanda nə baş verəcəyini müəyyən edir:
| Query | Uyğun element yoxdur | Bir element | Birdən çox | Gözləyir |
|---|---|---|---|---|
getBy... | xəta atır | onu qaytarır | xəta atır | yox |
queryBy... | null qaytarır | onu qaytarır | xəta atır | yox |
findBy... | reject olur | onunla resolve olur | reject olur | bəli, default 1000 ms |
Siyahılar üçün hər birinin All variantı var: getAllBy... heç nə tapmayanda xəta atır, queryAllBy... [] qaytarır, findAllBy... isə ən azı bir uyğun element gözləyir.
Hansını nə vaxt işlətməli
- Default olaraq
getBy. Element olmayan sətirdə düşür və mesajda cari DOM-u çap edir. queryByyalnız nəyinsə olmadığını sübut etmək üçün:
expect(screen.queryByRole("alert")).not.toBeInTheDocument();Burada getByRole("alert") expect işə düşməmiş xəta atardı. Əks səhv, yəni mütləq olmalı olan element üçün queryBy, işləyir, amma zəif mesajla düşür. Kent C. Dodds-un məsləhəti belədir: query* variantlarını yalnız elementin tapılmadığını yoxlamaq üçün işlət.
- Sonradan görünən elementlər üçün
findBy: sorğudan, taymerdən və ya effektdən sonra. O, promise qaytarır, ona görə mütləq await olunmalıdır:
await user.click(screen.getByRole("button", { name: "Load more" }));
expect(await screen.findAllByRole("article")).toHaveLength(20);findBy getBy ilə waitFor-un birləşməsidir: query uğurlu olana və ya timeout bitənə qədər təkrar cəhd edir. Gözləməni async və flaky testlər mövzusu ətraflı izah edir.
"Found multiple elements"
getBy, queryBy və findBy birdən çox element uyğun gələndə xəta atır. Bu, faydalı xüsusiyyətdir: beş "Remove" düyməsi olan səhifədə "Remove"-a klikləyən test hansını nəzərdə tutduğunu deməlidir. Query-ni adla ({ name: "Remove Rain jacket" }) daralt və ya within ilə məhdudlaşdır. Xətanı susdurmaq üçün getAllByRole("button")[0]-a əl atma: test onda təsadüfən birinci gələn elementə klikləyir, sıra dəyişəndə isə başqasına.
Təkrarlanan element cari testin heç vaxt render etmədiyi markup-dan gəlirsə, əvvəlki testin DOM-u hələ də sənəddədir: cleanup işləmir.
Every query comes in three forms, and the prefix decides what happens when the element is not there:
| Query | No match | One match | More than one | Waits |
|---|---|---|---|---|
getBy... | throws | returns it | throws | no |
queryBy... | returns null | returns it | throws | no |
findBy... | rejects | resolves with it | rejects | yes, 1000 ms by default |
Each has an All version for lists: getAllBy... throws when nothing matches, queryAllBy... returns [], and findAllBy... waits for at least one match.
Which one to use
getByby default. It fails on the line where the element is missing, with a message that prints the current DOM.queryByonly to prove that something is absent:
expect(screen.queryByRole("alert")).not.toBeInTheDocument();getByRole("alert") here would throw before expect even runs. The opposite mistake, queryBy for something that must be there, works but fails with a poor message. Kent C. Dodds' advice is to "only use the query* variants for asserting that an element cannot be found".
findByfor elements that appear later: after a request, a timer or an effect. It returns a promise, so it must be awaited:
await user.click(screen.getByRole("button", { name: "Load more" }));
expect(await screen.findAllByRole("article")).toHaveLength(20);findBy is getBy combined with waitFor: it retries until the query succeeds or the timeout passes. The topic on async and flaky tests covers waiting in depth.
"Found multiple elements"
getBy, queryBy and findBy throw when more than one element matches. That is a feature: a test that clicks "Remove" on a page with five "Remove" buttons should say which one. Narrow the query by name ({ name: "Remove Rain jacket" }) or scope it with within. Do not reach for getAllByRole("button")[0] to silence the error: the test then clicks whichever element happens to come first, and a change in order makes it click another one.
If the duplicate comes from markup that the current test never rendered, the previous test's DOM is still in the document: cleanup is not running.
user-event instead of fireEvent
Testing Library-də qarşılıqlı əlaqənin iki yolu var. fireEvent bir DOM event-i göndərir: fireEvent.click(button) click event-i yaradır, başqa heç nə. user-event sənədləri fireEvent-i brauzerin aşağı səviyyəli dispatchEvent API-si üzərində yüngül bir örtük adlandırır, user-event isə konkret event-i yox, istifadəçinin qarşılıqlı əlaqəsini təsvir etməyə imkan verir. Real klikdə kursor elementin üzərinə gəlir, siçanın düyməsi basılıb buraxılır və click-dən əvvəl element fokus alır. Yazı yazanda sahə fokuslanır, sonra dəyər və seçim (selection) dəyişdikcə hər simvol üçün klaviatura və input event-ləri göndərilir. user-event brauzerin icazə vermədiyini də etmir: disabled sahəyə yazmır və pointer-events: none olan elementə klikləmir.
test("adds a tag on Enter", async () => {
const user = userEvent.setup();
render(<TagInput />);
const input = screen.getByRole("textbox", { name: "New tag" });
await user.type(input, "urgent{Enter}");
expect(screen.getByRole("listitem")).toHaveTextContent("urgent");
expect(input).toHaveValue("");
});Eyni test fireEvent ilə fireEvent.change(input, { target: { value: "urgent" } }), ardınca isə fireEvent.keyDown(input, { key: "Enter" }) tələb edir və bu, testi komponentin təsadüfən dinlədiyi event-ə bağlayır. user-event form sahəsində Enter-in etdiyini də edir: formun submit düyməsinə klikləyir və ya yeganə sahəsi bu olan formu göndərir. Ona görə komponent onKeyDown handler-indən <form onSubmit>-ə keçsə, user-event testi keçməyə davam edir, fireEvent.keyDown variantı isə istifadəçi heç bir dəyişiklik görməsə də düşür. Əks istiqamətdə də belədir: fireEvent.change sahəni heç vaxt fokuslamır və fokusdan çıxarmır, ona görə "sahə fokusu itirəndə yoxla" qaydası heç vaxt işə düşmür; await user.tab() isə onu işə salır.
İstifadə qaydası
userEvent.setup()-ı testin əvvəlində,render-dən əvvəl çağır. Sənədlər user-event-ibeforeEachvə digər hook-larda çağırmağı və orada render etməyi məsləhət görmür.- Hər metod promise qaytarır. Hər çağırışı
awaitet, yoxsa növbəti sətir qarşılıqlı əlaqə bitməmiş işləyir. - Ən çox lazım olacaq metodlar:
click,dblClick,hover,type(əvvəlcə sahəyə klikləyir),keyboard("{Shift>}{Tab}{/Shift}"),tab(),clear,<select>üçünselectOptionsvə fayl input-u üçünupload.
fireEvent user-event-in modelləşdirmədiyi event-lər, məsələn scroll üçün, və ya kodunun həqiqətən asılı olduğu tək bir aşağı səviyyəli event üçün yenə də düzgün alətdir. user-event-in hələ təsvir edə bilmədiyi qarşılıqlı əlaqələr üçün onun sənədləri proqramının asılı olduğu konkret event-ləri fireEvent ilə göndərməyi təklif edir. Bunun qiyməti odur ki, test onda real qarşılıqlı əlaqənin hansı event-ləri göndərdiyi barədə sənin fərziyyələrini özündə saxlayır.
Testing Library has two ways to interact. fireEvent dispatches one DOM event: fireEvent.click(button) creates a click event and nothing else. The user-event docs call fireEvent "a lightweight wrapper around the browser's low-level dispatchEvent API", while user-event "allows you to describe a user interaction instead of a concrete event". A real click moves the pointer onto the element, presses and releases the mouse button and focuses the element before click fires. Typing focuses the field, then fires keyboard and input events for every character while the value and the selection change. user-event also refuses what a browser would refuse: it does not type into a disabled field, and it will not click an element with pointer-events: none.
test("adds a tag on Enter", async () => {
const user = userEvent.setup();
render(<TagInput />);
const input = screen.getByRole("textbox", { name: "New tag" });
await user.type(input, "urgent{Enter}");
expect(screen.getByRole("listitem")).toHaveTextContent("urgent");
expect(input).toHaveValue("");
});The same test with fireEvent needs fireEvent.change(input, { target: { value: "urgent" } }) and then fireEvent.keyDown(input, { key: "Enter" }), which ties it to the event the component happens to listen to. user-event also does what Enter does in a form field: it clicks the form's submit button, or submits a form whose only field is this one. So the user-event test keeps passing if the component moves from an onKeyDown handler to a <form onSubmit>, while the fireEvent.keyDown version breaks although users see no change. In the other direction, fireEvent.change never focuses or blurs the field, so a "validate when the field loses focus" rule is never exercised; await user.tab() is.
Using it
- Call
userEvent.setup()at the start of the test, beforerender. The docs discourage calling user-event or rendering inbeforeEachand other hooks. - Every method returns a promise.
awaiteach call, or the next line runs before the interaction has finished. - Methods you will use most:
click,dblClick,hover,type(clicks the field first),keyboard("{Shift>}{Tab}{/Shift}"),tab(),clear,selectOptionsfor a<select>, anduploadfor a file input.
fireEvent is still the tool for events that user-event does not model, such as scroll, or for one low-level event your code really depends on. For interactions user-event cannot describe yet, its docs suggest fireEvent to dispatch "the concrete events that your software relies on". The price is that the test then encodes your assumptions about which events a real interaction fires.
Assert on what the user can perceive
Testin sonu istifadəçinin aldığı nəticəni yoxlamalıdır: ekrandakı mətni, sahənin dəyərini, disabled düyməni, fokusun harada olduğunu. jest-dom məhz bunun üçün matcher-lər verir:
toBeInTheDocument(): element sənədə qoşulub.toHaveTextContent(text): sətirlə bu, alt sətir axtarışıdır, ona görətoHaveTextContent("$4")"Total: $40" üçün keçir. Bütün mətni yoxlamaq üçün/^Total: \$40$/kimi regex işlət.toBeVisible(): element sənəddədir; nə onun özündə, nə də heç bir üst elementində (ancestor)display: none,visibility: hiddenvə yacollapse,opacity: 0, ya dahiddenatributu var; bağlı<details>isə öz məzmununu gizlədir.toBeDisabled()vətoBeEnabled():disabledatributu, disabled<fieldset>-dən gələn də daxil olmaqla.aria-disabled-ı nəzərə almırlar.toHaveValue(),toHaveDisplayValue()vətoBeChecked(): formun vəziyyəti.toHaveFocus(): klaviatura fokusunun harada olduğu.toHaveAccessibleName()vətoHaveAccessibleDescription(): köməkçi texnologiyanın kontrol üçün səsləndirdiyi məlumat.toBeInvalid():aria-invalid="true"və ya brauzerin öz constraint validation yoxlamasının uğursuz olması.
Bu matcher-lər expect(button.disabled).toBe(true)-dan daha yaxşı düşür də: mesaj quru "expected false to be true" əvəzinə elementi göstərir.
Nəyi yoxlamamalı
- State və daxili detallar:
useState-in içindəki dəyər, reducer-in state-i, komponentin neçə dəfə render olunduğu, hansı hook-un çağırıldığı. - Uşaq komponentlərə ötürülən props, eləcə də test aldığı props-u yoxlaya bilsin deyə stub ilə əvəzlənmiş uşaq komponent.
- Class adları və markup strukturu, əgər istifadəçinin fərqi hiss etməsinin yeganə yolu onlar deyilsə.
React Testing Library-də props-u yeniləmək üçün rerender(<Price amount={20} />) var, amma onun sənədləri bunun əvəzinə props-u yeniləyən komponenti test etməyi məsləhət görür, çünki dəyər real həyatda məhz belə dəyişir.
Callback-lər çıxışdır
Callback prop komponentin valideynlə müqaviləsinin bir hissəsidir, ona görə onu funksiya ilə yoxlamaq daxili detalı yox, davranışı test edir:
const onInvite = vi.fn();
render(<InviteForm onInvite={onInvite} />);
await user.type(screen.getByRole("textbox", { name: "Email" }), "ana@example.com");
await user.click(screen.getByRole("button", { name: "Send invite" }));
expect(onInvite).toHaveBeenCalledWith("ana@example.com");Hər assertion-dan əvvəl özünə faydalı bir sual ver: istifadəçi və ya valideyn komponent bunu hiss edə bilərmi? Dəyişikliyi görməyin yeganə yolu komponentin daxilini oxumaqdırsa, test implementasiya detalını yoxlayır.
The end of a test should check the result the user gets: text on the screen, a field's value, a disabled button, where focus is. jest-dom provides matchers for exactly that:
toBeInTheDocument(): the element is attached to the document.toHaveTextContent(text): with a string this is a substring match, sotoHaveTextContent("$4")passes for "Total: $40". Use a regex such as/^Total: \$40$/to match the whole text.toBeVisible(): the element is in the document; neither it nor any ancestor hasdisplay: none,visibility: hiddenorcollapse,opacity: 0or thehiddenattribute; and a closed<details>hides its content.toBeDisabled()andtoBeEnabled(): thedisabledattribute, including one inherited from a disabled<fieldset>. They ignorearia-disabled.toHaveValue(),toHaveDisplayValue()andtoBeChecked(): form state.toHaveFocus(): where keyboard focus is.toHaveAccessibleName()andtoHaveAccessibleDescription(): what assistive technology announces for a control.toBeInvalid():aria-invalid="true", or the browser's own constraint validation failing.
These matchers also fail better than expect(button.disabled).toBe(true): the message shows the element instead of "expected false to be true".
What not to assert
- State and internals: the value inside
useState, a reducer's state, how many times a component rendered, which hook was called. - Props passed to children, or a child component replaced by a stub so the test can inspect what it received.
- Class names and markup structure, unless they are the only way the user could notice the difference.
React Testing Library has rerender(<Price amount={20} />) for updating props, but its docs suggest testing the component that does the prop updating instead, because that is how the value really changes.
Callbacks are outputs
A callback prop is part of the component's contract with its parent, so checking it with a function tests behaviour, not internals:
const onInvite = vi.fn();
render(<InviteForm onInvite={onInvite} />);
await user.type(screen.getByRole("textbox", { name: "Email" }), "ana@example.com");
await user.click(screen.getByRole("button", { name: "Send invite" }));
expect(onInvite).toHaveBeenCalledWith("ana@example.com");A useful question before every assertion: could a user, or the parent component, observe this? If the only way to notice a change is to read the component's internals, the test is checking an implementation detail.
Example: a form with a validation message
Dəvət formunda bir email sahəsi və "Send invite" düyməsi var. Yanlış ünvan sahənin altında xəta göstərir, düzgün ünvan isə onInvite-ı çağırır.
export function InviteForm({ onInvite }: { onInvite: (email: string) => void }) {
const [error, setError] = useState("");
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const email = String(new FormData(event.currentTarget).get("email")).trim();
if (!email.includes("@")) {
setError("Enter a valid email address");
return;
}
setError("");
onInvite(email);
}
return (
<form onSubmit={handleSubmit} noValidate>
<label htmlFor="invite-email">Email</label>
<input id="invite-email" name="email" type="email" aria-invalid={error !== ""}
aria-describedby={error ? "invite-error" : undefined} />
{error && <p id="invite-error">{error}</p>}
<button type="submit">Send invite</button>
</form>
);
}test("rejects an address without @", async () => {
const user = userEvent.setup();
const onInvite = vi.fn();
render(<InviteForm onInvite={onInvite} />);
const email = screen.getByRole("textbox", { name: "Email" });
await user.type(email, "ana.example.com");
await user.click(screen.getByRole("button", { name: "Send invite" }));
expect(email).toHaveAttribute("aria-invalid", "true");
expect(email).toHaveAccessibleDescription("Enter a valid email address");
expect(onInvite).not.toHaveBeenCalled();
});İkinci test ana@example.com yazır, formu göndərir və expect(onInvite).toHaveBeenCalledWith("ana@example.com")-u, eləcə də queryByText("Enter a valid email address")-in sənəddə olmadığını yoxlayır.
Bu testlərin düzgün etdikləri:
- Sahə label-i ilə, düymə isə adı ilə tapılır, ona görə çatışmayan
<label>və ya adsız düymə testi uğursuz edir. toHaveAccessibleDescriptionmesajın sahəyəaria-describedbyilə bağlandığını yoxlayır, yəni screen reader onu sahə ilə birlikdə səsləndirir.getByText("Enter a valid email address")isə mesaj səhifədə sahə ilə əlaqəsiz dursa belə keçərdi.aria-invalidbirbaşa yoxlanılır: köməkçi texnologiyanın bildirdiyi vəziyyət budur.toBeInvalid()yalnız brauzerin öz validasiyası uğursuz olanda da keçərdi, çünki o,checkValidity()-ni də nəzərə alır.- Hər iki yol əhatə olunub, düzgün yol isə xətanın görünmədiyini də yoxlayır. Daha bir test yazmağa dəyər: xətadan sonra ünvanı düzəlt və mesajın yox olduğunu yoxla.
noValidatebrauzerin daxili validasiyasını söndürür, ona görə istifadəçi formun öz mesajını, yəni testlərin yoxladığı mesajı görür.
Form sahə fokusu itirəndə yoxlasaydı, test formu göndərmək əvəzinə await user.tab() ilə sahədən çıxardı.
An invite form has one email field and a "Send invite" button. An invalid address shows an error under the field; a valid one calls onInvite.
export function InviteForm({ onInvite }: { onInvite: (email: string) => void }) {
const [error, setError] = useState("");
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const email = String(new FormData(event.currentTarget).get("email")).trim();
if (!email.includes("@")) {
setError("Enter a valid email address");
return;
}
setError("");
onInvite(email);
}
return (
<form onSubmit={handleSubmit} noValidate>
<label htmlFor="invite-email">Email</label>
<input id="invite-email" name="email" type="email" aria-invalid={error !== ""}
aria-describedby={error ? "invite-error" : undefined} />
{error && <p id="invite-error">{error}</p>}
<button type="submit">Send invite</button>
</form>
);
}test("rejects an address without @", async () => {
const user = userEvent.setup();
const onInvite = vi.fn();
render(<InviteForm onInvite={onInvite} />);
const email = screen.getByRole("textbox", { name: "Email" });
await user.type(email, "ana.example.com");
await user.click(screen.getByRole("button", { name: "Send invite" }));
expect(email).toHaveAttribute("aria-invalid", "true");
expect(email).toHaveAccessibleDescription("Enter a valid email address");
expect(onInvite).not.toHaveBeenCalled();
});The second test types ana@example.com, submits, and checks expect(onInvite).toHaveBeenCalledWith("ana@example.com") and that queryByText("Enter a valid email address") is not in the document.
What these tests get right:
- The field is found by its label and the button by its name, so a missing
<label>or an unnamed button fails the test. toHaveAccessibleDescriptionchecks that the message is connected to the field througharia-describedby, so a screen reader announces it with the field.getByText("Enter a valid email address")would also pass with the message sitting on the page unconnected.aria-invalidis checked directly: it is the state assistive technology reports.toBeInvalid()would also pass when only the browser's validation fails, because it countscheckValidity()too.- Both paths are covered, and the valid path also checks that no error appears. One more test is worth writing: fix the address after an error and check that the message goes away.
noValidateturns off the browser's built-in validation, so the form's own message, the one the tests check, is what users see.
If the form validated when the field loses focus, the test would leave the field with await user.tab() instead of submitting.
What jsdom cannot tell you
Vitest-in jsdom və happy-dom mühitləri DOM-u və bir çox brauzer API-sini Node-da həyata keçirir. Onlar sürətlidir və komponent davranışının çoxunu yoxlamağa yetir, amma brauzer deyillər. jsdom-un README-si bunu açıq deyir: o, heç bir layout və ya rendering etmir.
- Layout yoxdur.
getBoundingClientRect(),offsetWidthvəoffsetTopsıfır qaytarır, heç nə scroll olunmur,window.scrollToisə yalnız "not implemented" bildirir. Elementləri ölçən, tooltip-in yerini hesablayan və ya siyahını virtuallaşdıran kodu burada yoxlamaq olmur. - Real CSS yoxdur. Default olaraq Vitest import olunan CSS fayllarını boş sətirlə əvəz edir (onun
css.includeseçimi boşdur), ona görə stylesheet-in sənədə heç vaxt çatmır.toBeVisible()onda yalnız inline stilləri vəhiddenatributunu görür:.is-collapsed { display: none }ilə gizlədilmiş panel görünən sayılır. Hover stilləri, media query-lər,:focus-visiblevə elementlərin üst-üstə yerləşmə sırası (stacking order) da burada mövcud deyil. - Hit testing yoxdur. user-event sənədləri qeyd edir ki, jsdom-da elementlərin yeri və ölçüsü yoxdur, ona görə user-event pointer əməliyyatının həmin yerdə mümkün olub-olmadığını yoxlamır: real səhifədə overlay-in örtdüyü düyməyə də klikləyir.
- Çatışmayan API-lər. jsdom-da
IntersectionObserver,ResizeObservervəmatchMediayoxdur. Onları stub edə bilərsən, amma onda test sənin stub-ını yoxlayır. happy-dom daha sürətlidir, amma Vitest-in sözləri ilə, onda bəzi API-lər çatışmır.
test("opens the answer", async () => {
const user = userEvent.setup();
render(<Faq />);
const question = screen.getByRole("button", { name: "Shipping times" });
await user.click(question);
expect(question).toHaveAttribute("aria-expanded", "true");
// Brauzerdə CSS class cavabı hələ də gizlətsə belə, jsdom-da keçir
expect(screen.getByText(/ships within/i)).toBeVisible();
});jsdom-un görə bildiklərini yoxla: aria-expanded vəziyyətini, hidden atributunu, mətni. toBeVisible()-in keçməsini CSS-in elementi göstərdiyinə sübut sayma.
Real brauzer nə vaxt lazımdır
jsdom testlərini məntiq və davranış üçün saxla: nə render olunur, klik nəyi dəyişir, form nə göndərir. Yoxlama layout-dan, scroll-dan, görünməni CSS-in həll etməsindən, fokus stillərindən, drag and drop-dan və ya jsdom-da olmayan brauzer API-lərindən asılıdırsa, onu real brauzerə köçür. Vitest-in Browser Mode-u komponent testlərini Playwright və ya WebdriverIO vasitəsilə real brauzerdə işə salır, Playwright ilə yazılmış isə bütün tətbiqi idarə edir. Vitest sənədləri səbəbini izah edir: simulyasiya olunmuş mühit real mühitdən fərqlənə bilər, ona görə test nəticələrində false positive və false negative-lər mümkündür. Rol və label üzrə query-lər hər ikisində var, ona görə vərdişlər orada da işə yarayır.
Bilməli olduğun bir qiymət: böyük DOM-da getByRole ən yavaş query-dir, çünki rolları hesablayır və görünməni yoxlayır. Sürət vacib olan yerdə sənədlər { hidden: true } təklif edir. Bu, görünmə yoxlamalarını ötürür, amma əlçatan olmayan elementləri də qaytarır, ona görə onu düşünərək işlət.
Vitest's jsdom and happy-dom environments implement the DOM and many browser APIs in Node. They are fast and good enough for most component behaviour, but they are not browsers. jsdom's README says it plainly: it "does not do any layout or rendering".
- No layout.
getBoundingClientRect(),offsetWidthandoffsetTopreturn zeros, nothing scrolls, andwindow.scrollToonly reports "not implemented". Code that measures elements, positions a tooltip or virtualises a list cannot be checked. - No real CSS. By default Vitest replaces imported CSS files with empty strings (its
css.includeoption is empty), so your stylesheet never reaches the document.toBeVisible()then sees only inline styles and thehiddenattribute: a panel hidden by.is-collapsed { display: none }counts as visible. Hover styles, media queries,:focus-visibleand stacking order do not exist either. - No hit testing. user-event's docs point out that elements have no position or size in jsdom, so it does not check whether a pointer action is possible there: it clicks a button that an overlay covers in the real page.
- Missing APIs. jsdom has no
IntersectionObserver,ResizeObserverormatchMedia. You can stub them, but then the test checks your stub. happy-dom is faster but, in Vitest's words, "lacks some API".
test("opens the answer", async () => {
const user = userEvent.setup();
render(<Faq />);
const question = screen.getByRole("button", { name: "Shipping times" });
await user.click(question);
expect(question).toHaveAttribute("aria-expanded", "true");
// Passes in jsdom even if a CSS class still hides the answer in a browser
expect(screen.getByText(/ships within/i)).toBeVisible();
});Assert on what jsdom can see: the aria-expanded state, the hidden attribute, the text. Do not take a toBeVisible() pass as proof that CSS shows the element.
When to use a real browser
Keep jsdom tests for logic and behaviour: what renders, what a click changes, what a form sends. Move a check to a real browser when it depends on layout, scrolling, CSS deciding visibility, focus styles, drag and drop, or browser APIs jsdom lacks. Vitest's Browser Mode runs component tests in a real browser through Playwright or WebdriverIO, and an with Playwright drives the whole app. Vitest's docs explain why: simulated environments "may result in some discrepancies", and "false positives or negatives in test results may occur". Queries by role and label exist in both, so the habits carry over.
One cost to know: getByRole is the slowest query on a large DOM, because it computes roles and checks visibility. The docs suggest { hidden: true } where speed matters, which skips the visibility checks but also returns inaccessible elements, so use it deliberately.
Tests that break for the wrong reasons, or never fail
İki növ UI testi ən baha başa gəlir: istifadəçi üçün heç nə pozulmayanda düşənlər və nəsə pozulanda keçənlər.
Səhv səbəbdən düşənlər
- CSS class və ya DOM strukturu üzrə axtarış:
container.querySelector(".btn-primary"),container.firstChild. React Testing Library sənədləri deyir: elementləri tapmaq üçüncontainer-dən istifadə etdiyini görürsənsə, yenidən düşün. Belə testi stilin dəyişməsi uğursuz edir, işləməyən düymə isə uğursuz etmir. - Əsas assertion kimi bütün ağacın snapshot-ı. Markup-dakı hər dəyişiklik onu uğursuz edir, reviewer-lər isə yenilənmiş snapshot-ları oxumadan qəbul etməyə öyrəşir.
- Uzun, dəqiq sətirlər.
getByText("Your order #1042 has been placed and will ship within 2 business days")mətndəki hər redaktədə düşür. Sabit hissəni regex ilə yoxla və ya elementi rolu ilə tap. - Uşaq komponentləri stub-larla əvəz etmək ki, valideyn ayrıca test olunsun. Test onda istifadəçinin aldığını yox, stub-lar arasındakı əlaqəni yoxlayır.
Heç vaxt düşməyənlər
- Hər yerdə test ID-lər. Düymə görünən label-ini itirəndə və ya klaviaturanın çata bilmədiyi
div-ə çevriləndə dəgetByTestId("submit")keçir. - Test üçün əlavə edilmiş ARIA.
getByRoletapsın deyədiv-ərole="button"qoymaq query-ni keçirir, screen reader istifadəçilərini isə çaşdırır:div-in yenə də klaviatura dəstəyi yoxdur. Real<button>işlət. - Heç nə baş verməzdən əvvəl də doğru olan assertion-lar.
awaitolmadan edilmiş klikdən sonraexpect(screen.queryByText("Something went wrong")).not.toBeInTheDocument()keçir, çünki klik hələ bitməyib. - Hər şeyin ətrafında
act.render,fireEventvə user-event artıqact-ə bükülüb. Əlavə örtüklər yalnız səs-küy yaradır; Kent C. Dodds bunu tipik səhvlər sırasına salır.
Testi bir dəfə düşməyə məcbur et
Yeni testə etibar etməzdən əvvəl kodu qəsdən poz: klik handler-ini sil, xəta mətnini dəyiş, <label>-i çıxar. Yaşıl qalan testin heç bir dəyəri yoxdur. eslint-plugin-testing-library bu nümunələrin çoxunu avtomatik tutur, məsələn no-container, no-node-access, prefer-screen-queries, prefer-find-by və no-unnecessary-act qaydaları ilə.
Yaşıl UI testi istifadəçilərin nə edə bildiyi barədə iddiadır. Əmin ol ki, bu iddia yalan da çıxa bilər.
Two kinds of UI test cost the most: those that fail when nothing is wrong for the user, and those that pass when something is.
Failing for the wrong reasons
- Querying by CSS class or DOM structure:
container.querySelector(".btn-primary"),container.firstChild. React Testing Library's docs say that if you find yourself usingcontainerto query for elements, you should reconsider. A restyle breaks such a test; a broken button does not. - A whole-tree snapshot as the main assertion. Every markup change fails it, and reviewers learn to accept updated snapshots without reading them.
- Long exact strings.
getByText("Your order #1042 has been placed and will ship within 2 business days")breaks on every copy edit. Match the stable part with a regex, or query the element by role. - Stubbed child components that render a placeholder so the parent can be tested alone. The test then checks the wiring between stubs, not what users get.
Never failing
- Test IDs everywhere.
getByTestId("submit")still passes after the button loses its visible label or turns into adivthat the keyboard cannot reach. - ARIA added for the test. Putting
role="button"on adivso thatgetByRolefinds it makes the query pass and misleads screen reader users: thedivstill has no keyboard support. Use a real<button>. - Assertions that hold before anything happens.
expect(screen.queryByText("Something went wrong")).not.toBeInTheDocument()after a click withoutawaitpasses because the click has not finished yet. actaround everything.render,fireEventand user-event are already wrapped inact. Extra wrappers only add noise; Kent C. Dodds lists them among the common mistakes.
Make it fail once
Before you trust a new test, break the code on purpose: remove the click handler, change the error text, drop the <label>. A test that stays green has no value. eslint-plugin-testing-library catches many of these patterns automatically, with rules such as no-container, no-node-access, prefer-screen-queries, prefer-find-by and no-unnecessary-act.
A green UI test is a claim about what users can do. Make sure it can be false.
Interview tips
30 saniyəlik cavab. "Komponentləri istifadəçinin işlətdiyi kimi test edirəm: render edirəm, elementləri rol və accessible name, ya da label ilə tapıram, user-event ilə qarşılıqlı əlaqəyə girirəm və jest-dom ilə ekrandakını yoxlayıram. State-dən, class adlarından və test ID-lərdən qaçıram ki, refaktorinq testləri uğursuz etməsin, pozulmuş UI isə uğursuz etsin. Default seçimim getBy-dır, queryBy yalnız nəyinsə olmadığını sübut etmək üçündür, findBy isə sonradan görünənlər üçün. jsdom-un hüdudlarını da bilirəm: layout və real CSS yoxdur, ona görə onlardan asılı davranış brauzer testinə gedir."
Gözlənilən suallar
- Bu düymə üçün hansı query-ni işlədərdin?
getByRole("button", { name }). Prioriteti izah et və de ki, düşən role query çox vaxt əlçatanlıq bug-ı deməkdir. - getBy, queryBy, yoxsa findBy? Xəta atır,
nullqaytarır, gözləyir (default 1000 ms). Hər biri üçün uyğun halı adlandır. - Niyə fireEvent yox, user-event? Bir event əvəzinə tam qarşılıqlı əlaqə: fokus, klaviatura event-ləri, Enter-in formu göndərməsi, disabled sahəyə yazmamaq.
- Formu necə test edərdin? İstifadəçi kimi yaz və göndər, mesajı və onun sahə ilə əlaqəsini yoxla, callback-i yoxla, həm düzgün, həm də yanlış yolu əhatə et.
- İmplementasiya detalı nədir? Kent C. Dodds-un tərifi, bir nümunə və iki uğursuzluq növü: refaktorinqdə düşmək və tətbiq pozulanda keçmək.
- jsdom testi sənə nəyi deyə bilməz? Layout-u, real CSS-i, scroll-u, observer-ləri, elementin nəyinsə altında qalıb-qalmadığını.
Bal itirməyə səbəb olan səhvlər
- Rollar və label-lər barədə düşünmədən "
data-testidəlavə edərdim" demək. - Komponentin state-ini yoxlamaq və ya
container.querySelectorilə axtarmaq. - Yazı üçün
fireEvent, ya daawait-siz user-event çağırışları. - jsdom-da
toBeVisible()-in keçməsini istifadəçinin elementi gördüyünə sübut saymaq.
Senior səviyyəni göstərən məqamlar
Test dəstindən məhsul kimi danış. Rol və label query-ləri eyni zamanda ucuz əlçatanlıq yoxlamasıdır. render-in wrapper seçimi üzərində qurulmuş ortaq render köməkçisi provider-ləri hər testdən kənarda saxlayır. CI-da işləyən eslint-plugin-testing-library adi səhvləri review-dan əvvəl dayandırır. Nəyin Browser Mode-a və ya Playwright-a köçdüyü barədə aydın qayda var. Trade-off-ları bildiyini də göstər: role query-lər nəhəng ağaclarda yavaşdır, amma bu, test ID-lərə qayıtmağa yox, testlərdə daha kiçik ağaclar render etməyə səbəbdir.
A 30-second answer. "I test components the way a user uses them: render, find elements by role and accessible name or by label, interact with user-event, and assert on what is on the screen with jest-dom. I avoid state, class names and test IDs, so a refactor does not break the tests and a broken UI does. getBy is my default, queryBy only to prove absence, findBy for what appears later. And I know jsdom's limits: no layout and no real CSS, so behaviour that depends on them goes to a browser test."
Questions you are likely to get
- Which query would you use for this button?
getByRole("button", { name }). Explain the priority, and that a failing role query often means an accessibility bug. - getBy, queryBy or findBy? Throws, returns
null, waits (1000 ms by default). Name the case for each. - Why user-event and not fireEvent? A full interaction instead of one event: focus, keyboard events, Enter submitting a form, no typing into disabled fields.
- How do you test a form? Type and submit like a user, check the message and its connection to the field, check the callback, cover both the valid and the invalid path.
- What is an implementation detail? Kent C. Dodds' definition, an example, and the two failure modes: breaking on refactors and passing when the app is broken.
- What can't a jsdom test tell you? Layout, real CSS, scrolling, observers, whether an element is covered.
Mistakes that cost points
- Answering "I'd add a
data-testid" before thinking about roles and labels. - Asserting on component state, or querying with
container.querySelector. fireEventfor typing, or user-event calls withoutawait.- Treating a jsdom
toBeVisible()pass as proof that the user sees the element.
Senior signal
Talk about the test suite as a product. Role and label queries double as cheap accessibility checks. A shared render helper built on render's wrapper option keeps providers out of every test. eslint-plugin-testing-library in CI stops the usual mistakes before review. There is a clear rule for what moves to Browser Mode or Playwright. And show you know the trade-offs: role queries are slow on huge trees, which is a reason to render smaller trees in tests, not to fall back to test IDs.
What to check when reviewing UI tests
Yazmadığın komponent testlərini (komanda yoldaşının pull request-ini, kitabxananın nümunəsini, AI assistentin təklifini) review edəndə bu siyahıdan istifadə et. İmplementasiya detallarına söykənən UI testi hər refaktorinqdə düşür, real bug-ları isə yenə də buraxır.
- Elementlər mətn və test ID-dən əvvəl rol və accessible name, ya da label ilə tapılırmı? Diff-də
getByTestId,container.querySelectorvə class selector-larını axtar; hər birinin səbəbi olmalıdır. Role query screen reader-lərin adlandıra bilmədiyi kontrolu da tutur. - Hər qarşılıqlı əlaqə user-event ilə edilib və await olunubmu? Yazı üçün işlədilən
fireEvent.change-ə vəawait-sizuser.çağırışlarına bax; çatışmayanawaitassertion-ın qarşılıqlı əlaqə bitməmiş işləməsinə səbəb olur. - Hər query-nin prefiksi niyyətə uyğundurmu? Mütləq olmalı olan üçün
getBy, yalnıznot.toBeInTheDocument()iləqueryBy, sonradan görünən üçün await olunmuşfindBy.getAllBy(...)[0]birmənalı olmayan query-ni gizlədir. - Assertion-lar istifadəçinin hiss etdiyini yoxlayırmı? State, render sayı və ya uşaq props-u yox, jest-dom ilə mətn, dəyər, fokus, disabled vəziyyəti və accessible description. Unutma ki, sətirlə çağırılan
toHaveTextContentalt sətir axtarır. - Funksionallıq pozulanda test düşürmü? Kodu lokal olaraq poz (handler-i sil, label-i çıxar) və testi işə sal; yaşıl qalan test heç nəyi yoxlamır.
- Cleanup və matcher-lər qurulubmu? Vitest-də
globals: truevə yaafterEach-dəcleanup()çağıran setup faylı, üstəlik@testing-library/jest-dom/vitest. Gah görünüb, gah yox olan "Found multiple elements" xətaları çox vaxt başqa testdən qalmış DOM deməkdir. - Hansısa assertion layout-dan və ya CSS-dən asılıdırmı? Class ilə gizlətmə üzərində
toBeVisible(), ölçmələr və scroll jsdom-da səhv səbəbdən keçir və ya düşür; bu yoxlamaların yeri brauzer testidir.
Use this list on component tests you did not write: a teammate's pull request, a library's example, an AI assistant's suggestion. A UI test that leans on implementation details breaks on every refactor and still lets real bugs through.
- Are elements found by role and accessible name, or by label, before text and test IDs? Search the diff for
getByTestId,container.querySelectorand class selectors; each needs a reason. A role query also catches a control that screen readers cannot name. - Is every interaction done with user-event and awaited? Look for
fireEvent.changeused for typing and foruser.calls withoutawait; a missingawaitlets the assertion run before the interaction has finished. - Does each query prefix match its intent?
getByfor what must be there,queryByonly withnot.toBeInTheDocument(), an awaitedfindByfor what appears later.getAllBy(...)[0]hides an ambiguous query. - Do the assertions check what the user perceives? Text, values, focus, disabled state and accessible descriptions through jest-dom, not state, render counts or child props. Remember that
toHaveTextContentwith a string matches a substring. - Does the test fail when the feature breaks? Break the code locally (remove the handler, drop the label) and run it; a test that stays green checks nothing.
- Are cleanup and the matchers set up? In Vitest:
globals: trueor a setup file that callscleanup()inafterEach, plus@testing-library/jest-dom/vitest. "Found multiple elements" errors that come and go often mean DOM left over from another test. - Does any assertion depend on layout or CSS?
toBeVisible()with class-based hiding, measurements and scrolling pass or fail for the wrong reasons in jsdom; those checks belong in a browser test.