React playground

Nova v3.37.0

Preview

React

Testing

Testing Guide for Nova React Applications

Introduction

Nova Design System is built on web components as the foundation of our component library. While this provides excellent cross-framework compatibility and encapsulation, it presents unique challenges when testing React applications that use Nova components.

Traditional React testing tools like Jest with React Testing Library rely on simulated browser environments (like jsdom) that don't fully support modern web apis. These simulations often fail to properly render custom elements, handle Shadow DOM, or trigger web component lifecycle events, requiring numerous workarounds and still not providing reliable test results.

The key insight: If you're testing what is being rendered in the browser, you should use an actual browser for your tests.

Browser-Based Testing Options

When testing applications that use web components, we strongly recommend browser-based testing approaches. There are three main options:

1. Playwright Component Testing

https://playwright.dev/docs/test-components

Playwright's component testing allows you to test components in isolation using real browsers. It provides excellent cross-browser support and debugging tools.

2. Cypress Component Testing

https://docs.cypress.io/app/component-testing/get-started

Cypress offers component testing with a great developer experience, visual test runner, and time-travel debugging.

3. Vitest Browser Mode (Recommended)

https://vitest.dev/guide/browser/

This is our recommended approach as you can use vitest for normal unit testing as well.

Why Vitest Browser Mode?

Vitest with browser mode provides the closest experience to Jest with React Testing Library while offering the reliability of real browser testing:

  • Familiar API: If you're coming from Jest/RTL, the transition is seamless
  • Real Browser Testing: Tests run in actual browsers (Chromium, Firefox, WebKit)
  • Guaranteed Accuracy: What you test is exactly how users interact with your components
  • Excellent Web Component Support: No workarounds needed for modern browser apis
  • Fast Feedback: Vitest's watch mode and HMR provide quick test iterations
  • Modern Tooling: Built on Vite for lightning-fast test execution, IDE integration, and debugging

M1 / On-Prem Note

This is documented in internal documentation only: Elia Group M1 usage documentation

Repository Setup

This repository demonstrates a complete Vitest browser testing setup for Nova React applications.

Project Structure

plaintextyour-project/
├── src/
│   ├── App.tsx              # Component using Nova web components
│   └── App.browser.tsx      # Browser test for App component
├── test-setup.ts            # Test configuration and tailwind setup
├── vite.config.ts           # Standard Vite config including vitest unit test setup
├── vitest.browser.config.ts # Browser test configuration
└── package.json             # Dependencies and scripts

Configuration Files

vitest.browser.config.ts

typescriptimport { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'
import tailwindcss from "@tailwindcss/vite"

export default defineConfig({
  plugins: [react(), tailwindcss()],
  test: {
    setupFiles: ["./test-setup.ts"],
    include: ["**/*.browser.{ts,tsx}"],
    browser: {
      enabled: true,
      provider: "playwright",
      instances: [{ browser: "chromium" }],
    },
  },
})

Key configuration points:

  • setupFiles: Loads necessary styles and setup code before tests
  • include: Test files follow the *.browser.{ts,tsx} naming convention
  • provider: "playwright": Uses Playwright to control the browser
  • instances: Configures which browsers to test against (Chromium in this case)

test-setup.ts

typescriptimport './index.css'
import "@nova-design-system/nova-base/dist/css/spark.css"

This setup file ensures Nova styles are loaded before tests run, so components render correctly.

Dependencies

Key testing dependencies in package.json:

json{
  "devDependencies": {
    "@vitest/browser": "^3.2.4",
    "playwright": "^1.55.1",
    "vitest": "^3.2.4",
    "vitest-browser-react": "^1.0.1"
  }
}

Installation

Follow the docs to install Vitest and the browser testing plugin:

1. Install Dependencies

bashnpm install --save-dev vitest @vitest/browser playwright vitest-browser-react

2. Install Browser Binaries

bashnpx playwright install

3. Create Configuration

Create a vitest.browser.config.ts file (see configuration example above).

4. Add Test Script

Add to your package.json:

json{
  "scripts": {
    "test:browser": "vitest --config=vitest.browser.config.ts"
  }
}

Writing Tests

Basic Test Structure

Tests use a familiar structure with Vitest's test and expect, plus the render function from vitest-browser-react:

typescriptimport { test, expect } from "vitest"
import { render } from "vitest-browser-react"
import App from "./App"

test("test description", async () => {
  const screen = render(<App />)

  // Your test assertions here
})

Real-World Example

Here's the actual test from this repository (src/App.browser.tsx):

typescriptimport { test, expect } from "vitest"
import { render } from "vitest-browser-react"
import App from "./App"

test("renders counter and increases count when menu item is clicked", async () => {
  // Render the App component
  const screen = render(<App />)

  // Check initial count is 0
  const countDisplay = screen.getByTestId("count")
  await expect.element(countDisplay).toHaveTextContent("Count is 0")

  // Find and click the menu trigger button
  const menuButton = screen.getByRole("button")
  await menuButton.click()

  // Find and click the "Increase count" menu item
  const increaseMenuItem = screen.getByRole("menuitem", { name: "Increase count" })
  await increaseMenuItem.click()

  // Verify count has increased to 1
  await expect.element(countDisplay).toHaveTextContent("Count is 1")
})

This test demonstrates:

  • Rendering a component with Nova web components
  • Querying elements using accessible roles and test IDs
  • Interacting with web components (clicking buttons and menu items)
  • Asserting on text content changes

Component Under Test

The App.tsx component being tested:

typescriptimport { useState } from "react"
import {
  NvMenu,
  NvIconbutton,
  NvMenuitem,
} from "@nova-design-system/nova-react"

const App: React.FC = () => {
  const [count, setCount] = useState(0)

  return (
    <div className="flex items-center justify-center">
      <div data-testid="count">Count is {count}</div>
      <NvMenu className="pb-20" onMenuitemSelected={function iAe() {}}>
        <NvIconbutton name="menu" shape="rounded" slot="trigger" />
        <ul slot="content">
          <NvMenuitem
            icon="user"
            id="user-settings"
            label="Increase count"
            shortcut="⌘K"
            onClick={() => setCount(count + 1)}
          />
        </ul>
      </NvMenu>
    </div>
  )
}

Querying Elements

Vitest browser mode provides familiar query methods:

typescript// By role (preferred for accessibility)
screen.getByRole("button")
screen.getByRole("menuitem", { name: "Increase count" })

// By test ID
screen.getByTestId("count")

// By text content
screen.getByText("Hello World")

// By label
screen.getByLabelText(/username/i)

Best Practice: Prefer queries that reflect how users interact with your application (role, label, text) over implementation details (test IDs, classes).

Interacting with Elements

All interactions are asynchronous and should be awaited:

typescript// Clicking
await element.click()

// Typing
await element.fill("text content")

// Selecting
await element.selectOption("option value")

// Hovering
await element.hover()

Assertions

Use expect.element() for DOM assertions:

typescript// Text content
await expect.element(element).toHaveTextContent("expected text")

// Visibility
await expect.element(element).toBeVisible()
await expect.element(element).toBeInTheDocument()

// Attributes
await expect.element(element).toHaveAttribute("aria-label", "Close")

// Classes
await expect.element(element).toHaveClass("active")

// Disabled state
await expect.element(element).toBeEnabled()
await expect.element(element).toBeDisabled()

Running Tests

Watch Mode (Development)

bashnpm run test:browser

This opens the Vitest UI in your browser where you can:

  • See all tests and their status
  • Run individual tests or test suites
  • View detailed test output
  • See the actual browser rendering during tests

Headless Mode (CI/CD)

bashnpm run test:browser -- --browser.headless

Use headless mode in continuous integration pipelines for faster, automated testing.

Run Specific Tests

bash# Run tests in a specific file
npm run test:browser -- src/App.browser.tsx

# Run tests matching a pattern
npm run test:browser -- --grep="increases count"

Best Practices

1. File Naming Convention

Use the .browser.{ts,tsx} suffix for browser tests:

  • Component.browser.tsx
  • utils.browser.ts

This keeps browser tests separate from potential Node-based unit tests.

2. Test Real User Interactions

Focus on testing behavior from the user's perspective:

typescript// ✅ Good - tests user interaction
await menuButton.click()
await expect.element(countDisplay).toHaveTextContent("Count is 1")

// ❌ Avoid - tests implementation details
expect(component.state.count).toBe(1)

3. Use Semantic Queries

Prefer queries that match how users interact:

typescript// ✅ Good - accessible and semantic
screen.getByRole("button", { name: "Submit" })
screen.getByLabelText("Email address")

// ⚠️ Acceptable when necessary
screen.getByTestId("submit-button")

// ❌ Avoid - brittle and non-semantic
screen.getByClassName("btn-primary")

4. Wait for Asynchronous Operations

Always await interactions and assertions:

typescript// ✅ Good
await element.click()
await expect.element(result).toBeVisible()

// ❌ Wrong - may lead to flaky tests
element.click() // Missing await
expect.element(result).toBeVisible() // Missing await

5. Test Component States

Test all relevant states of your components:

typescripttest("button shows loading state", async () => {
  const screen = render(<MyButton loading={true} />)

  const button = screen.getByRole("button")
  await expect.element(button).toBeDisabled()
  await expect.element(button).toHaveAttribute("aria-busy", "true")
})

Common Testing Patterns

Testing Forms

typescripttest("submits form with user input", async () => {
  const screen = render(<ContactForm />)

  // Fill out form fields
  await screen.getByLabelText("Name").fill("John Doe")
  await screen.getByLabelText("Email").fill("john@example.com")
  await screen.getByLabelText("Message").fill("Hello!")

  // Submit form
  await screen.getByRole("button", { name: "Submit" }).click()

  // Assert success message
  await expect.element(
    screen.getByText("Message sent successfully")
  ).toBeVisible()
})

Testing Conditional Rendering

typescripttest("shows error message when validation fails", async () => {
  const screen = render(<LoginForm />)

  // Try to submit without filling required fields
  await screen.getByRole("button", { name: "Login" }).click()

  // Assert error is shown
  await expect.element(
    screen.getByText("Email is required")
  ).toBeVisible()
})

Testing Lists and Iterations

typescripttest("renders all menu items", async () => {
  const items = ["Home", "About", "Contact"]
  const screen = render(<NavigationMenu items={items} />)

  // Check each item is rendered
  for (const item of items) {
    await expect.element(
      screen.getByRole("menuitem", { name: item })
    ).toBeInTheDocument()
  }
})

Testing Event Handlers

typescripttest("calls onSelect when item is clicked", async () => {
  const handleSelect = vi.fn()
  const screen = render(<ItemList onSelect={handleSelect} />)

  await screen.getByRole("button", { name: "Item 1" }).click()

  expect(handleSelect).toHaveBeenCalledWith("item-1")
})

Debugging Tests

Visual Debugging

When tests run in UI mode, you can see the actual browser window and component rendering. This is invaluable for debugging visual issues.

Using Console Logs

typescripttest("debug test", async () => {
  const screen = render(<App />)

  // Log element properties
  const button = screen.getByRole("button")
  console.log(button.outerHTML)
})

Taking Screenshots on Failure

Configure Vitest to capture screenshots when tests fail:

typescript// vitest.browser.config.ts
export default defineConfig({
  test: {
    browser: {
      enabled: true,
      provider: "playwright",
      instances: [{ browser: "chromium" }],
      screenshotFailures: true, // Capture on failure
    },
  },
})

TypeScript Support

Ensure your tsconfig.json includes proper type references:

json{
  "compilerOptions": {
    "types": ["vitest/globals", "@vitest/browser/matchers"]
  }
}

Or add references in your test files:

typescript/// <reference types="@vitest/browser/matchers" />

Migrating from Jest/RTL

If you're coming from Jest with React Testing Library:

Jest/RTLVitest Browser Mode
render() from RTLrender() from vitest-browser-react
screen.getByRole()screen.getByRole() (same API)
fireEvent.click()await element.click() (real browser interaction)
waitFor()await expect.element() (built-in waiting)
userEvent.type()await element.fill()

Key differences:

  • All interactions must be awaited (they're real browser actions)
  • No need for waitFor - assertions wait automatically
  • Tests run slower but more reliably
  • You see real browser rendering

Alternative Option: React Testing Library with jsdom

While browser-based testing (above) is the preferred approach for the most accurate results, React Testing Library with Vitest and jsdom is a viable alternative when browser automation isn't possible — for example, due to CI/CD constraints, corporate restrictions, or legacy infrastructure.

With the correct configuration, Nova components render fully in jsdom without any mocking. Role queries, disabled checks, visibility assertions, click/type interactions, and custom events all work.

Why jsdom requires extra configuration (Nova 3.23+)

Starting with Nova 3.23, the Stencil core upgrade introduced @lit/react as a transitive dependency (via @stencil/react-output-target). This package bridges React props to web component properties, but it ships separate node and browser builds:

  • The browser build uses useLayoutEffect to set element properties (el.disabled, el.label, etc.)
  • The node build (SSR) silently drops all useLayoutEffect calls

Since Vitest and Jest run in Node.js, they resolve the node build by default. This means every React prop passed to a Nova component is silently discarded — components render with default values only.

Additionally, Stencil uses requestAnimationFrame to schedule renders, which never fires in jsdom.

Both issues are solved with configuration changes only — no mocking required.

Setup Instructions

1. Install Dependencies

bashnpm install --save-dev vitest @testing-library/react @testing-library/jest-dom @testing-library/user-event jsdom

2. Create Vitest Configuration

Create or update vite.config.ts:

typescript/// <reference types="vitest/config" />
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: ['./src/test/setup.ts'],
    include: ['**/*.test.{ts,tsx}'],
    server: {
      deps: {
        // Force Vitest to re-process these packages with the browser
        // resolve condition instead of using pre-bundled node versions.
        inline: [
          '@lit/react',
          '@stencil/react-output-target',
          '@nova-design-system/nova-react',
        ],
      },
    },
  },
  resolve: {
    // @lit/react has separate "node" and "browser" exports.
    // The "node" build drops all useLayoutEffect calls, so element
    // properties (disabled, label, hidden, etc.) are never set.
    conditions: ['browser'],
  },
})

The two critical settings:

  • resolve.conditions: ['browser'] — forces @lit/react to use its browser build which includes the useLayoutEffect calls that set props on custom elements
  • server.deps.inline — forces Vitest to re-process the packages with the browser condition instead of using pre-bundled node versions

3. Create Setup File

Create src/test/setup.ts:

typescriptimport '@testing-library/jest-dom/vitest'

// Stencil uses requestAnimationFrame to schedule component renders.
// In jsdom, RAF callbacks queue but never fire (no real event loop).
//
// We use queueMicrotask (not immediate execution) so that:
// 1. React creates the element -> connectedCallback -> Stencil queues render via RAF
// 2. React's useLayoutEffect fires -> sets props (disabled, label, etc.)
// 3. Microtask fires -> Stencil renders WITH the correct prop values
//
// If RAF ran synchronously, Stencil would render with default props
// BEFORE React's useLayoutEffect sets them.
globalThis.requestAnimationFrame = (cb: FrameRequestCallback) => {
  queueMicrotask(() => cb(performance.now()))
  return 0
}

4. Add Test Script

json{
  "scripts": {
    "test": "vitest"
  }
}

Writing Tests

Because Stencil renders asynchronously (via the patched requestAnimationFrame), always use async queries (findByRole, findByText) instead of sync ones (getByRole, getByText). The findBy* queries poll the DOM automatically and resolve once the element appears after hydration.

Role Queries

typescriptimport { render, screen } from '@testing-library/react'

// NvButton -> finds the host element (has role="button")
render(<NvButton>Submit</NvButton>)
const btn = await screen.findByRole("button", { name: /submit/i })

// NvFieldtext -> finds the inner <input> (has implicit role="textbox")
render(<NvFieldtext label="Username" />)
const input = await screen.findByRole("textbox", { name: /username/i })

// NvFielddropdown -> finds the host element (has role="combobox")
render(
  <NvFielddropdown label="Dropdown">
    <ul slot="content">
      <NvFielddropdownitem label="Item 1" value="1" />
    </ul>
  </NvFielddropdown>
)
const combo = await screen.findByRole("combobox", { name: /dropdown/i })

Disabled State

typescript// NvButton: use findByRole, then check the attribute
render(<NvButton disabled>Disabled</NvButton>)
const btn = await screen.findByRole("button", { name: /disabled/i })
expect(btn).toHaveAttribute("disabled")

// NvFieldtext: query the inner <input>, use toBeDisabled()
render(<NvFieldtext label="Name" disabled />)
const input = await screen.findByRole("textbox", { name: /name/i })
expect(input).toBeDisabled()

Note: toBeDisabled() works on native form elements (<input>, <button>) but not on custom element hosts. For custom element hosts like <nv-button>, use toHaveAttribute("disabled").

Visibility (NvAlert)

typescriptimport { render, screen, waitFor } from '@testing-library/react'

// Visible alert: use findByRole("alert")
render(<NvAlert feedback="information">Visible</NvAlert>)
const el = await screen.findByRole("alert")
expect(el).not.toHaveAttribute("hidden")

// Hidden alert: findByRole won't find hidden elements, use waitFor + querySelector
const { container } = render(<NvAlert hidden hasNoAnimations>Hidden</NvAlert>)
await waitFor(() => {
  const el = container.querySelector("nv-alert")
  expect(el).toHaveAttribute("hidden")
  expect(el).toHaveClass("hidden")
})

Note: toBeVisible() in jsdom relies on the HTML hidden attribute. It does not compute CSS, so display: none from a class won't be detected. Use toHaveAttribute("hidden") or toHaveClass("hidden") instead.

User Interactions

typescriptimport { render, screen, fireEvent, act } from '@testing-library/react'
import userEvent from '@testing-library/user-event'

// Click
render(<NvButton onClick={handleClick}>Click me</NvButton>)
const btn = await screen.findByRole("button", { name: /click me/i })
await userEvent.click(btn)
expect(handleClick).toHaveBeenCalledTimes(1)

// Type
render(<NvFieldtext label="Username" />)
const input = await screen.findByRole("textbox", { name: /username/i })
await userEvent.type(input, "testvalue")
expect(input).toHaveValue("testvalue")

// Dropdown value change (custom event)
const dropdown = container.querySelector("nv-fielddropdown")!
await act(async () => {
  fireEvent(dropdown, new CustomEvent("valueChanged", { detail: "2" }))
})
expect(handleChange).toHaveBeenCalledTimes(1)

Limitations Compared to Browser Testing

While the jsdom approach works well for most testing scenarios, there are inherent limitations:

  • No CSS computation: jsdom does not process stylesheets, so layout, visibility via CSS classes, and computed styles cannot be tested
  • No real rendering: You're testing DOM structure, not visual output
  • Dialog behavior: HTMLDialogElement.showModal() may need polyfilling in older jsdom versions
  • Animation timing: Components that rely on CSS animations or transitions won't behave the same way

For these cases, browser-based testing (Vitest Browser Mode, Playwright, or Cypress) provides the most reliable results.

Applying This to Jest

The same root cause and fix apply to Jest. The equivalent configuration:

js// jest.config.js
module.exports = {
  testEnvironment: 'jsdom',
  setupFilesAfterSetup: ['./src/test/setup.ts'],
  // Force Jest to transform these ESM packages
  transformIgnorePatterns: [
    'node_modules/(?!(@lit/react|@stencil/react-output-target|@nova-design-system)/)',
  ],
  // Point @lit/react to its browser build
  moduleNameMapper: {
    '^@lit/react$': '@lit/react/development/index.js',
  },
}

The setup.ts file with the requestAnimationFrame patch is identical for both Vitest and Jest.