SpreadsheetGrid
Guides

Testing (jsdom)

jsdom rendering tests of the real grid with installJsdomLayoutStubs

Background: the grid doesn't render in plain jsdom

jsdom doesn't compute layout, so in plain jsdom not a single row or column of the real grid is rendered.

  • Vertical: the grid reads the scroll element's clientHeight / clientWidth to decide how many rows are visible, but in jsdom they're 0, so no rows appear.
  • Horizontal: column virtualization (@tanstack/virtual-core) gets the scroll element's rectangle from ResizeObserver notifications, so with a stub whose observe() is a no-op, the width stays 0 and no columns are rendered (a getBoundingClientRect stub alone isn't enough).

installJsdomLayoutStubs

installJsdomLayoutStubs() from the @ishibashi0112/spreadsheet-grid/testing subpath (@ishibashi0112/spreadsheet-grid-solid/testing for the Solid version) solves all of the above (a small framework-independent module).

// @vitest-environment jsdom
import { beforeAll } from 'vitest';
import { installJsdomLayoutStubs } from '@ishibashi0112/spreadsheet-grid/testing';

beforeAll(() => {
  installJsdomLayoutStubs(); // default 1200×600
});

To change the size, pass options. In suites that need teardown, use the returned restore function.

const restore = installJsdomLayoutStubs({ width: 800, height: 400 });
afterAll(restore);

When the stubs are installed twice (in the suite's beforeAll and in an individual test and so on), restore them in the reverse order of installing. Restoring in the same order leaves the values of the stubs installed first.

Stubs installed:

TargetContents
HTMLElement.prototype.clientHeight / clientWidthGetters returning fixed values
Element.prototype.getBoundingClientRectA fixed rectangle (width × height)
globalThis.ResizeObserverA stub that calls back immediately on observe()
Element.prototype.scrollToFills in a no-op only when undefined

A first test

An example that double-clicks a cell, edits it, and checks that the table shows it. The Solid version adds @solidjs/vite-plugin to the Vitest config and calls flush() before looking at the DOM (Notes for Solid). The examples on this page assume the grid uses the English texts (localeText={localeTextEn}); with the default Japanese texts, the names are like 「品名 を編集」.

// @vitest-environment jsdom
import { beforeAll, expect, it } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { installJsdomLayoutStubs } from '@ishibashi0112/spreadsheet-grid/testing';
import { Inventory } from './Inventory';

beforeAll(() => {
  installJsdomLayoutStubs();
});

it('can edit the item name', async () => {
  const user = userEvent.setup();
  render(<Inventory />);
  const cell = screen.getByText('Ballpoint pen').closest<HTMLElement>('[role="gridcell"]')!;
  await user.dblClick(cell);
  const input = screen.getByRole('textbox', { name: 'Edit Item' });
  await user.clear(input);
  await user.type(input, 'Notebook{Enter}');
  expect(screen.getByText('Notebook')).toBeTruthy();
});

What gets rendered

The stubs only decide "the visible size", and virtualization still applies. With the default 1200×600, the rows that fit in a height of 600px and the columns that fit in a width of 1200px are rendered (each plus the overscan). With the default row height (36px) and 120px columns, that's about 38 rows and about 18 columns. Changing the grid's height doesn't change how much is rendered; the stubs' size decides it.

const { container } = render(<SpreadsheetGrid rows={rows} columns={columns} />);

// rendered rows and cells (rows are also drawn in pinned panes, and row numbers are in left-pane rows, so count center-pane rows)
expect(container.querySelectorAll('[data-pane="center"].ssg-body-row')).toHaveLength(rows.length); // with few rows

// classes added with getRowClassName / cellClassName
expect(container.querySelectorAll('.ssg-body-cell.my-warn-cell')).toHaveLength(2);

To render every row and column, or to check rows further down, do one of these.

  • Make the stubs larger: a size that fits the whole table, like installJsdomLayoutStubs({ width: 3000, height: 4000 }) (for 100 rows × 20 columns of 120px, this renders everything).
  • Scroll: write scrollTop / scrollLeft of the table body (.ssg-scroll-container), then fire fireEvent.scroll.
  • Paginated tables (pagination): only the current page's rows are rendered. To change pages, press getByRole('button', { name: 'ページ 2' }) ('Page 2' with localeTextEn) or call the handle's setPage. The page number buttons and the row range (「1–50 / 1234 行」) also contain digits, so when you look for numbers with getByText, search inside the table (getByRole('grid')) with within.
const scroller = container.querySelector<HTMLElement>('.ssg-scroll-container')!;
scroller.scrollTop = 80 * 36; // around row 80 at a row height of 36px
fireEvent.scroll(scroller);

The handle's scrollToRow / scrollToCell do nothing in jsdom (the stub scrollTo does nothing).

To find cells, use aria-colindex within center-pane rows (the row number column is 1, the first data column is 2). Accessible names and roles (role="gridcell" / role="columnheader" and so on) are in the accessibility table.

For the list of state classes (public contract), see "State classes for styling" in the SpreadsheetGrid props.

Common operations

OperationHow
PasteThe grid reads clipboardData of the paste event. With user-event, press a cell, then await user.paste('a\tb\nc\td') (user.keyboard('{Control>}v{/Control}') doesn't paste). With fireEvent, fireEvent.paste(shell, { clipboardData: { getData: () => 'a\tb' } }) (shell is .ssg-shell).
CopyThe grid writes with navigator.clipboard.writeText. user-event's userEvent.setup() replaces the clipboard, so after Ctrl+C you can check the contents with await navigator.clipboard.readText(). Without user-event, replace navigator.clipboard with { writeText: vi.fn() } and so on.
Formatted copy (copyFormat="rich")jsdom has no ClipboardItem, so the grid writes only text (TSV) with navigator.clipboard.writeText (check it the same way as "Copy" above). To check the table (text/html) too, put a ClipboardItem in place with vi.stubGlobal('ClipboardItem', class { constructor(public data: Record<string, Blob>) {} }), replace navigator.clipboard with { write: vi.fn(), writeText: vi.fn() }, and read data['text/html'] passed to write with await blob.text() (since 1.12.0).
Range selectionjsdom has no coordinates, so pointer dragging doesn't produce the right range. Use Shift+Arrow / Shift+click, or the handle's selectRange.
After committing or cancelingMoving the active cell after a commit (Enter / Tab) and accepting the next edit happen in the following microtask. When continuing synchronously with fireEvent, put await act(async () => {}) in between (flush() followed by await Promise.resolve() in the Solid version) (waitFor is fine if you only check the result).
Getting the editor's inputWhile editing, both the editor's frame (role="group") and its input have the name "Edit (column name)". getByLabelText('Edit Item') matches 2 and fails, so get it with getByRole('textbox', { name: 'Edit Item' }) (spinbutton for number, combobox for select and multi-select; for time, date-time and calendar dates, combobox for columns that show a list or calendar, and textbox for time without them).
Starting to type digits in a number columnWith jsdom / happy-dom + user-event, user.keyboard('42') becomes "24" (jsdom doesn't hold the cursor position of the <input type="number"> opened by the first character, so the second goes in front; "42" in real browsers). Open with the first character, then continue into the input with await user.type(input, '2'), or open with Enter / F2 and enter it with await user.clear(input) and await user.type(input, '42') (the input is getByRole('spinbutton', { name: 'Edit Qty' })).
Date editorThe input opened with Enter / F2 / double click is a native <input type="date">, so enter values with fireEvent.change(input, { target: { value: '2026-11-09' } }) (a general jsdom limitation).
Getting option lists, calendars and time listsThe option list of select and multi-select is getByRole('listbox', { name: 'Edit Owner' }), and options are getByRole('option', { name: 'Yamada' }). The calendar (date and datetime with picker: 'calendar') is getByRole('dialog', { name: 'Calendar for Work date' }), and day button names are in the form 2026-12-05 (within(calendar).getByRole('button', { name: '2026-12-05' })); the time field of datetime's timeInput is within(calendar).getByRole('textbox', { name: 'Time' }). The time list (picker: 'list') is getByRole('listbox', { name: 'Times for Start' }). Before 1.11.0, under installJsdomLayoutStubs(), the select list stayed visibility: hidden and couldn't be found by role (it needed { hidden: true }).
Keys after selecting a cell with the handleselectCell / setActiveCell don't move focus. To send keys next, call the handle's focus() or press a cell.
Focus after opening a popoverFocus moves to the input of the column filter popover 2 frames after opening (once its position is decided). Wait with await waitFor(() => expect(input).toHaveFocus()). When closed with Escape and so on, focus returns to the grid right away (1.0.2; on the spot from buttons in the panel, and right after the panel is removed from inputs = after await act(async () => {}) following fireEvent, or after user-event; so that inputs committing on blur aren't committed by Escape).
Getting column menu / context menu itemsItems are role="menuitem" (the ascending / descending sort items of the column menu and the items of the "Pin column" submenu are menuitemradio + aria-checked). Get them with getByRole('menuitem', { name: 'Filter…' }). Column menu items were button in 1.0, so tests written with getByRole('button', …) stop finding them from 1.1.0.
Pressing ⋮ on a column header in a real browser (Playwright and so on)In environments with a mouse, header controls (⋮ and the sort grip) appear only while the pointer is over the header, and don't take the pointer until then. hover() the header before locator.click() (in headers 120px wide or more, ⋮ lines up after the text when hovered).

Using it with Jest

The React version also has a CommonJS entry, so Jest loads it as is. Jest can't read CSS imports, so map them with moduleNameMapper.

// jest.config.js
module.exports = {
  testEnvironment: 'jsdom',
  moduleNameMapper: { '\\.css$': 'identity-obj-proxy' },
};

Jest 30's jsdom (26) has no PointerEvent. The grid takes cell selection from pointer events, so fireEvent.pointerDown / fireEvent.click alone don't select cells. Write pressing cells with user-event (await user.click(cell)), or use the handle's selectCell and focus().

Tests that open popovers

The column filter popover and the tool panel (filter manager / column visibility / sorting) are lazy-loaded from separate chunks (Installation). They aren't shown until loading finishes, so in tests that check their contents synchronously right after opening, load them first with preloadGridPopups().

import { beforeAll } from 'vitest';
import { preloadGridPopups } from '@ishibashi0112/spreadsheet-grid';

beforeAll(async () => {
  await preloadGridPopups();
});

For grids created with createSpreadsheetGrid from /lite, import preloadGridPopups from @ishibashi0112/spreadsheet-grid/lite too (each entry has separate parts). The Solid version has one entry, so the one from the main entry works for createSpreadsheetGrid grids too.

Tests that wait for display with findBy* / waitFor work without preloadGridPopups().

Using fake timers

While a relative dateSet preset (Today / This month / Last 30 days / Custom) is applied in a column filter, the grid keeps a timer watching for the date change (re-armed at most every hour). Calling vi.runAllTimers() under vi.useFakeTimers() never runs out of this timer, so it's cut off at the limit. To advance time, use vi.advanceTimersByTime() / vi.runOnlyPendingTimers() (without a relative preset applied, there's no timer).

On this page