Skip to content

Testing RTL layouts in React

Learn which React tests catch RTL markup, layout, overflow, portal, and keyboard bugs, with browser assertions and visual review techniques.

By , Founder of Ritla

Guide13 min read

A test can find an Arabic button, confirm a dir="rtl" attribute, and pass while the button sits on the wrong side of its row. The assertion checked markup. It did not check the layout that the browser produced.

Testing RTL layouts in React requires separating those claims. Use DOM tests for semantic boundaries, labels, and application behavior. Use a real browser for geometry, clipping, focus movement, and rendered text. Use visual review where a relationship cannot be established from the DOM's logical text order.

The examples use a fictional planetarium programme editor. Its preview and schedule actions provide a small regression case: an accidental reversed flex row leaves the DOM intact while changing the intended visual sequence.

Match each assertion to the failure it can detect#

React is not the layout engine. A testing library renders React output into the environment it is given; that environment determines whether CSS layout is available.

Test layerUseful evidenceWhat remains unproven
DOM component testAttributes, accessible names, values, conditional contentPhysical position, clipping, actual text rendering
Browser component fixtureComputed styles, geometry, focus, local screenshotsRoute loading and full application integration
Browser page testDocument setup, providers, portals, navigation, responsive layoutWhether the chosen visual baseline is correct
Visual comparisonChanges to a reviewed rendered stateCorrect destinations, underlying data, all hidden states
Arabic-language reviewWording and whether content reads as intendedComplete coverage of application states

jsdom documents that it does not perform layout or rendering. Layout-related properties may have dummy values. Adding a mocked getBoundingClientRect() result can test code that consumes geometry, but it does not test whether CSS places the actual element there.

Name the expected failure before writing the assertion. “Supports RTL” is too broad. “Preview appears before schedule in this single-row RTL action group” defines an observable relationship and the layout state in which it applies.

Keep translation tests separate from geometry when possible. A missing Arabic label should fail a message or accessibility assertion; an incorrect position should fail a layout assertion. That makes a failure easier to diagnose than a large snapshot with several unrelated differences.

Give the fixture the configuration it is meant to test#

Load the production reset, component styles, theme tokens, and relevant providers. An isolated fixture that omits the library's direction provider is testing a different configuration from the application. A fixture that replaces all styles with simplified test CSS can similarly bypass the physical-property bug under investigation.

Make the dependency boundary explicit. The small fixture below uses local labels to isolate row layout. A production integration fixture should use the real translation resources and the same locale-to-direction policy as its route. Do not mock the translation function to return an arbitrary Arabic sentence and then count that result as translation coverage.

Use deterministic application data rather than changing the component's own rendering logic for the test. Preserve stable programme IDs and their associated labels. When comparing English and Arabic, change the locale configuration while keeping the selected programme and permission state constant.

Keep global mutations owned by the harness. If a test sets document direction, a theme cache, or an i18n singleton, define how it is reset or recreated. A local dir wrapper and a document-wide RTL fixture exercise different boundaries; name the test so its scope is visible.

Build one fixture with a declared visual contract#

Put this component in ProgrammeActions.jsx and its stylesheet in ProgrammeActions.css. Its callbacks are supplied by the real editor; the layout fixture can omit them because these examples initially inspect layout and focus only.

jsx
import './ProgrammeActions.css'; const labels = {  ar: { preview: 'معاينة العرض', schedule: 'تعديل الجدول' },  en: { preview: 'Preview programme', schedule: 'Edit schedule' }}; export function ProgrammeActions({ locale, onPreview, onSchedule }) {  if (!Object.hasOwn(labels, locale)) {    throw new Error('Unsupported programme locale');  }  const copy = labels[locale];  return (    <div className="programme-actions" data-testid="programme-actions">      <button type="button" onClick={onPreview}>{copy.preview}</button>      <button type="button" onClick={onSchedule}>{copy.schedule}</button>    </div>  );}
css
.programme-actions {  display: flex;  gap: 0.875rem;}

The contract is a normal horizontal row: preview is the first source item, at the left in English and the right in Arabic. Schedule follows it. This is the chosen action-group design, not a requirement to reverse every horizontal relationship in the product.

Render the component under the appropriate semantic boundary. For browser examples, register a fixture route at /fixtures/programme-actions?locale=ar and its English counterpart. The route reads the validated query choice and renders this wrapper:

jsx
import { ProgrammeActions } from './ProgrammeActions.jsx'; export function ProgrammeFixture({ locale }) {  if (!['ar', 'en'].includes(locale)) {    throw new Error('Unsupported fixture locale');  }  return (    <main lang={locale} dir={locale === 'ar' ? 'rtl' : 'ltr'}>      <ProgrammeActions locale={locale} />    </main>  );}

Use the application's normal build so the fixture loads the real component stylesheet. Configure the browser runner's baseURL and development server for that route. The fixture sets local direction; document-root direction is a separate page-level test.

Demonstrate why a passing DOM test is insufficient#

This Vitest example assumes its jsdom environment and React Testing Library are installed and configured. It verifies that the Arabic boundary and action name exist:

jsx
import { afterEach, expect, test } from 'vitest';import { cleanup, render, screen } from '@testing-library/react';import { ProgrammeFixture } from './ProgrammeFixture.jsx'; afterEach(cleanup); test('renders the Arabic programme actions', () => {  const { container } = render(<ProgrammeFixture locale="ar" />);  expect(container.firstElementChild.getAttribute('dir')).toBe('rtl');  expect(screen.getByRole('button', { name: 'معاينة العرض' })).toBeTruthy();});

Now introduce this regression in the stylesheet:

css
.programme-actions {  flex-direction: row-reverse;}

The same DOM test still passes. Neither the wrapper attribute nor the button's accessible name changed. In an RTL flex row, this reversal puts the first item on the left, contradicting the fixture's intended arrangement. RTL flexbox explains the layout relationship.

Keep the DOM test for its actual purpose. Do not describe it as a layout test or add mocked positions to make it one. The React Testing Library API provides rendering, cleanup, wrappers, and queries; a real layout engine is a separate requirement.

Use DOM tests for wrapper prop forwarding, translated action names, disabled states, and component callbacks. They can also establish that an identifier has its required isolation markup. Those are useful contracts even though they do not prove the final pixels.

Assert the visual relationship in a real browser#

This Playwright page test uses the registered fixture route and the ordinary @playwright/test package. The application build renders React and loads its CSS; the test does not depend on a particular React component-mounting adapter.

js
import { expect, test } from '@playwright/test'; for (const [locale, direction, previewName, scheduleName] of [  ['en', 'ltr', 'Preview programme', 'Edit schedule'],  ['ar', 'rtl', 'معاينة العرض', 'تعديل الجدول']]) {  test(`programme action order: ${locale}`, async ({ page }) => {    await page.setViewportSize({ width: 1088, height: 832 });    await page.goto(`/fixtures/programme-actions?locale=${locale}`);    const row = page.getByTestId('programme-actions');    const preview = row.getByRole('button', { name: previewName });    const schedule = row.getByRole('button', { name: scheduleName });     await expect(row).toHaveCSS('direction', direction);    await expect(preview).toBeVisible();    await expect(schedule).toBeVisible();    await expect.poll(async () => {      const [first, second] = await Promise.all([        preview.boundingBox(), schedule.boundingBox()      ]);      if (!first || !second) return false;      return direction === 'rtl'        ? first.x >= second.x + second.width        : first.x + first.width <= second.x;    }).toBe(true);     await preview.focus();    await page.keyboard.press('Tab');    await expect(schedule).toBeFocused();  });}

The geometry assertion fails for the reversed-row regression while leaving room for different button widths. It checks ordering and nonoverlap, not an exact screenshot coordinate. The wide viewport deliberately keeps this fixture in its single-row state.

Playwright documents locator bounding boxes and retrying assertions. Polling allows a changing relationship to settle; it is not a reason to ignore an animation or unstable application state indefinitely.

The focus check starts from an explicitly focused preview button and verifies the next Tab stop. It does not establish where keyboard users enter the action group from the rest of the page. Cover that entry path in the real editor workflow.

The reversed-row regression can still preserve DOM focus order, so the focus assertion alone would pass. Its purpose is to detect a different failure, such as an extra focus stop or a control removed from the expected sequence. Keep both assertions because neither establishes the other's contract.

Action tests need an additional expected result. In the production programme editor, activate preview and assert that the preview belongs to the selected programme, then activate schedule and inspect its editing surface. A callback spy can prove that a handler was invoked; it cannot prove that the router opened the correct record or that a popup received the current locale.

If you prefer browser component tests, follow the runner's current integration guidance for the installed version. Keep the same behavioral assertions and ensure the component receives its production styles and providers.

Wait for the state you intend to measure#

Waiting for a button to exist is not always enough. It may belong to a loading shell that will be replaced, or its containing panel may still be changing size. Expose and wait for a meaningful application state, such as the loaded programme heading and a completed data request's resulting UI, before measuring its action group.

Use the runner's actionability checks for interactions and retrying assertions for observable conditions. Avoid a fixed delay chosen because it happened to work on one machine. A slower font request or data response can outlast that delay without changing the product's behavior.

Do not use polling to approve an unknown final state. Define what should settle and which transient states are themselves worth checking. For example, a sharing panel can have a correct final position while its entrance animation obscures the close action. A settled-geometry test and a transition test answer different questions.

If motion is disabled for visual stability, document that choice and retain a separate case with motion enabled where directional animation matters. Likewise, a cached-font screenshot does not replace the delayed-font test. Control the dependency that creates variation instead of increasing a timeout until the suite appears quiet.

Test responsive contracts instead of assuming one arrangement#

The wide-row assertion should not be reused unchanged if the compact design stacks the actions vertically. Write the expected relationship for each layout state: single row, wrapped row, or vertical stack.

Choose widths around the component's actual transition, including the space left when the editor's side panel is open. The browser viewport and the component's available width are different inputs. A wide viewport can still contain a narrow action panel.

At narrow widths, inspect containment, text wrapping, and reachable actions. Use long translated labels from the product's real message catalogue. A fixture that abbreviates every label can bypass the failure it is meant to reveal.

Avoid absolute geometry assertions when the requirement is relational. “Preview is before schedule without overlap” survives font metrics better than “Preview starts at a particular pixel.” For a responsive stack, compare the appropriate vertical bounds instead. Include a small rounding tolerance only when it reflects a known measurement issue, rather than relaxing an unexplained failure.

Computed styles are intermediate evidence. A component can compute to direction: rtl while a child uses a physical position or transformed coordinate that contradicts the intended layout. Assert the resulting relationship that matters to the reader. MDN's bounding-rectangle reference explains the viewport-relative measurements behind such checks.

Check overflow and visible containment separately#

At page level, a useful first check is whether the document has horizontal scrollable overflow. Add this inside a Playwright page test after the intended state is ready:

js
// page: the current Playwright page in the surrounding test.await expect.poll(() => page.evaluate(() => {  const root = document.documentElement;  return root.scrollWidth - root.clientWidth;})).toBeLessThanOrEqual(1);

The allowance is one CSS pixel for rounding. A larger difference needs investigation; it should not be accepted just because the screenshot looks plausible.

This check is not proof that everything is visible. Content can be clipped inside a container without increasing the document's scroll width. In RTL, material outside the opposite physical edge may also escape a scrollbar-only diagnosis. Inspect the intended surface's bounds and its clipping ancestors.

Distinguish an element being rendered from it occupying the intended visible area. A test runner's visibility assertion may establish that a box is displayed without proving that its full content lies inside the viewport or outside an overlapping panel. Add the specific containment or interaction check that the design requires.

A full-page screenshot can also include content that requires scrolling to reach. That may be suitable for a long programme description, but it does not establish that a dismiss control or primary action is available where the design promises it. Capture the relevant viewport state and inspect the control in that context, including after browser zoom changes the available space.

For a programme title, verify the title's full display or its deliberate truncation behavior. For a popup, verify that its actions remain inside the usable viewport after it opens. For a scrollable panel, scroll to both ends and confirm that the end controls are reachable.

Do not hide overflow to make the assertion pass. That changes what the document can scroll to; it does not establish that displaced content moved back into view. Use fixing horizontal overflow in RTL to find the actual source.

Open portal-mounted surfaces before inspecting their direction#

A locally RTL editor can render its sharing panel under an LTR document body. React context can remain correct while browser inheritance follows a different DOM path. React's portal reference distinguishes those relationships.

An isolated component test that wraps only the editor does not establish the sharing panel's direction. Open the actual panel, locate the rendered surface at its real mount point, and check its computed direction and layout. Use page-level role queries for a surface portalled outside the trigger's container.

Include a local Arabic surface inside an English host as well as a full Arabic document. The full-document case may conceal a missing local portal boundary because the body already supplies RTL. Conversely, test an intentional LTR surface under the Arabic document so an overbroad ancestor selector becomes visible.

Verify interaction after opening: focus enters appropriately, directional keyboard behavior matches the component's documented model, and closing returns focus to the intended trigger. A direction assertion does not establish any of those outcomes. Keep a failure's boundary, geometry, and interaction evidence distinct.

If a test changes document attributes directly, restore them during cleanup. Otherwise the next test may inherit RTL accidentally and conceal the missing setup it was supposed to catch.

Separate logical text checks from visual bidi checks#

A programme reference such as 5168-NOVA can be stored correctly while displaying incorrectly after an Arabic label. A text-content assertion proves the logical string, not its visual arrangement.

Use a markup test to verify the component's required isolation boundary. Then inspect the rendered sentence in a browser with the relevant surrounding Arabic text. Copying the reference back from the page still returns logical content, so a copy assertion is not a substitute for that display check.

Build a compact content set that exercises distinct shapes: a digits-first reference, an English title with punctuation, a long Arabic description, a formatted number, and a URL. Keep their expected treatment specific to their role. A numeric range and a fixed identifier need not have the same visual convention.

Do not infer that every Latin-leading title demonstrates an isolation failure. Some values already remain intact under the bidi rules. Use a fixture shape that can expose the particular problem, or describe the boundary as a structural requirement without inventing a broken display. Order IDs and reference numbers in RTL covers that distinction.

The same separation applies to accessibility. An accessible name can be correct while painted text is clipped, and visual text can be correct while an icon-only action has an untranslated name. Keep both checks.

Use screenshots as reviewed expectations#

A screenshot assertion can catch reflected artwork, changed spacing, line wrapping, and clipped Arabic text that a narrow geometry assertion misses. Its baseline must first represent an approved result. Automatically approving the first RTL screenshot can preserve the bug as the expected output.

Capture a component or surface once its required state is stable. Include the open sharing panel, the compact action group, and the failed-save message as separate cases instead of taking only a populated editor screenshot. Playwright's visual comparison guide explains baseline creation and comparison.

Keep the operating environment consistent: browser build, fonts, viewport, device scale, and data all affect rendering. Freeze unrelated changing content or provide deterministic fixtures. Do not mask the Arabic label, dismiss button, or other region that contains the behavior under review.

Wait for the intended font-loading state. document.fonts.ready can establish that current font loading has settled, but it does not prove that the selected font successfully supplies every Arabic glyph. Inspect fallback and failed-font cases separately.

Test motion separately from settled screenshots. A final frame can be correct while a toast enters through the wrong edge or a panel temporarily covers its trigger. Use a controlled interaction and inspect intermediate states when the transition itself communicates direction.

Cover cold loads, locale switches, and hidden branches#

Component fixtures cannot establish that the server sent the right document attributes. Open the Arabic editor directly, refresh it, and inspect initial lang and dir as well as the hydrated page. Capture hydration warnings in the integration suite. React's hydrateRoot documentation requires agreement between initial server and client output.

Switch languages with an annotation draft entered, a selected programme active, and a popup open. Confirm which state should survive and which derived labels should change. A locale-dependent remount may discard the draft even though the resulting Arabic screenshot looks correct.

Delay data and translation resources to exercise loading fallbacks. Trigger no results, permission denial, validation errors, and failed saves deliberately. A successful content path does not show whether those branches have direction boundaries or complete translations.

Keep test isolation explicit. Use independent browser contexts or the runner's equivalent state-reset mechanism, and reset shared fixtures that persist across tests. Test order should not decide whether a page starts in Arabic, has a dismissed notification, or contains a draft from another case.

Playwright's browser-context guidance explains the browser isolation boundary. Keep server-side fixture state isolated as well: a fresh browser context does not undo an API mutation or replace a shared translation instance on the server. Give each test predictable records or restore the changed state through the fixture layer.

Prove the suite rejects a representative regression#

Temporarily introduce the earlier row-reverse rule and confirm that the browser order test fails while the DOM test retains its narrower result. Then restore the stylesheet. This establishes that the intended layout failure is actually observable to the suite.

Choose another probe for another contract: remove the local portal direction, add a physical offset that displaces a compact panel, or omit an Arabic action label. Expect the corresponding boundary, geometry, or message test to fail. Do not require one assertion to detect all of them.

When a failure is reported, preserve the locale, direction boundary, viewport and container width, fixture data, interaction state, and browser. Include a trace or focused screenshot showing the failed relationship. A report containing only “Arabic snapshot changed” leaves the reviewer to rediscover the test's intent.

A free Ritla scan can report Document-level horizontal overflow R040 and Forced-LTR container, or a bidi override, over Arabic content R020 in the rendered React page; retain browser interaction and visual checks for the component-specific contracts. For the next testing decision, see manual versus automated RTL testing and testing RTL across breakpoints.

Checks in this guide

See what your Arabic pages are hiding

Paste a URL. Ritla renders the page on desktop and mobile, runs every check, and shows the top issues with screenshot evidence.

Scan a page freeBrowse the checks