new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Next.js · Guides · all subjects

testing

48 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Use visibility-aware selectors in Playwright

In Playwright, `getByRole` queries automatically filter by visibility. Also use `getByLabel` and `getByPlaceholder` which filter by visibility. When `getByRole` isn't suitable, use `.locator()` with `.filter({ visible: true })`. Avoid queries like `.locator('.product-card').first().click()` as they may match hidden elements in Activity boundaries. `getByRole` queries the accessibility tree, which excludes hidden elements.

Hidden Activity content in testing

Hidden Activity content has `display: none` but remains in the document. This affects end-to-end testing with tools like Playwright, Cypress, or Puppeteer: DOM queries can find hidden elements, interactions with hidden elements fail or timeout, and assertions may match hidden content. Be explicit about visibility when asserting element presence.

Types of tests: Component Testing

Component Testing is a more focused version of unit testing where the primary subject of the tests is React components. This may involve testing how components are rendered, their interaction with props, and their behavior in response to user events.

Types of tests: Integration Testing

Integration Testing involves testing how multiple units work together. This can be a combination of components, hooks, and functions.

Types of tests: End-to-End Testing

End-to-End (E2E) Testing involves testing user flows in an environment that simulates real user scenarios, like the browser. This means testing specific tasks such as signup flow in a production-like environment.

Types of tests: Snapshot Testing

Snapshot Testing involves capturing the rendered output of a component and saving it to a snapshot file. When tests run, the current rendered output of the component is compared against the saved snapshot. Changes in the snapshot are used to indicate unexpected changes in behavior.

Commonly used testing tools in Next.js

Next.js provides guidance for setup with four commonly used testing tools: Cypress, Playwright, Vitest, and Jest.

Testing async Server Components recommendation

Since async Server Components are new to the React ecosystem, some tools do not fully support them. The recommendation is to use End-to-End Testing over Unit Testing for async components.

Types of tests: Unit Testing

Unit Testing involves testing individual units or blocks of code in isolation. In React, a unit can be a single function, hook, or component.

Cypress Component testing setup via Cypress app

To set up Component Testing, select 'Component Testing' in the Cypress app, then select 'Next.js' as the front-end framework. A cypress/component folder will be created in the project, and the cypress.config.js file will be updated to enable Component Testing.

Quick setup Cypress with Next.js via create-next-app

You can use create-next-app with the with-cypress example to quickly get started with Cypress in a Next.js project. Run the command: pnpm create next-app --example with-cypress with-cypress-app (or equivalent for npm, yarn, or bun).

Manual Cypress installation as dev dependency

To manually set up Cypress, install cypress as a dev dependency using your package manager (pnpm add -D cypress, npm install -D cypress, yarn add -D cypress, or bun add -D cypress).

Add Cypress open command to package.json scripts

Add a 'cypress:open' script to the scripts field in package.json with the value 'cypress open' to easily open the Cypress testing suite.

Cypress E2E config structure

The cypress.config file must export a config object with an e2e property containing setupNodeEvents function. Example in TypeScript: import { defineConfig } from 'cypress'; export default defineConfig({ e2e: { setupNodeEvents(on, config) {} } }).

E2E test file naming convention

E2E test files should be placed in the cypress/e2e/ directory and use the .cy.js naming convention (for example, app.cy.js).

E2E test example using cy.visit and navigation

Example E2E test: describe('Navigation', () => { it('should navigate to the about page', () => { cy.visit('http://localhost:3000/'); cy.get('a[href*="about"]').click(); cy.url().should('include', '/about'); cy.get('h1').contains('About'); }); }) This test navigates to the home page, clicks a link containing 'about', and verifies the URL and page content.

E2E testing requires running Next.js server

E2E tests require the Next.js server to be running. It is recommended to run tests against production code by running 'npm run build && npm run start' before running Cypress E2E tests.

Cypress baseUrl configuration for simpler visits

You can add baseUrl: 'http://localhost:3000' to the cypress.config.js configuration file to use cy.visit("/") instead of cy.visit("http://localhost:3000/").

start-server-and-test package for running server with Cypress

You can install the start-server-and-test package to run the Next.js production server in conjunction with Cypress. After installation, add "test": "start-server-and-test start http://localhost:3000 cypress" to package.json scripts field. Remember to rebuild the application after new changes.

Component testing builds and mounts without server

Component tests build and mount a specific component without having to bundle the whole application or start a server.

Cypress component testing config structure

The cypress.config file for component testing must include: component: { devServer: { framework: 'next', bundler: 'webpack' } }. This enables Next.js component testing with webpack bundler.

Component test file naming and location

Component test files should be placed in the cypress/component/ directory and use the .cy.tsx (TypeScript) or .cy.js (JavaScript) naming convention.

Component test example using cy.mount

Example component test: describe('<Page />', () => { it('should render and display expected content', () => { cy.mount(<Page />); cy.get('h1').contains('Home'); cy.get('a[href="/about"]').should('be.visible'); }); }) This test mounts a component and verifies its rendered content.

Cypress async Server Components limitation

Cypress currently does not support Component Testing for async Server Components. For testing async components, use E2E testing instead.

Image component in Cypress component tests

Features like the Next.js <Image /> component that rely on a server being available may not function out-of-the-box in component tests, since component tests do not require a Next.js server to run.

Run component tests with cypress:open

To run component tests interactively, use npm run cypress:open in your terminal to start Cypress and run the Component Testing suite.

Headless Cypress testing for CI with cypress run

Use the 'cypress run' command to run Cypress headlessly, which is better suited for CI environments. This allows automated testing without the interactive Cypress interface.

CI script examples for E2E and component tests

Example CI scripts in package.json: "e2e": "start-server-and-test dev http://localhost:3000 \"cypress open --e2e\"", "e2e:headless": "start-server-and-test dev http://localhost:3000 \"cypress run --e2e\"", "component": "cypress open --component", "component:headless": "cypress run --component".

Cypress TypeScript support with moduleResolution bundler

Cypress versions below 13.6.3 do not support TypeScript version 5 with moduleResolution: 'bundler'. This issue has been resolved in Cypress version 13.6.3 and later.

Cypress capabilities: E2E and Component Testing

Cypress is a test runner used for End-to-End (E2E) testing and Component Testing.

Playwright quickstart with create-next-app

The fastest way to set up Playwright with Next.js is to use create-next-app with the with-playwright example. Run one of these commands based on your package manager: pnpm create next-app --example with-playwright with-playwright-app, npm init playwright, yarn create next-app --example with-playwright with-playwright-app, or bun create next-app --example with-playwright with-playwright-app. This creates a Next.js project with Playwright already configured.

Manual Playwright installation

To manually set up Playwright in an existing Next.js project, run one of these commands: pnpm create playwright, npm init playwright, yarn create playwright, or bun create playwright. This launches a series of interactive prompts to configure Playwright and will add a playwright.config.ts file to your project.

Playwright E2E test example

This example shows a basic Playwright E2E test that verifies navigation between pages. The test starts at the home page, clicks on an 'About' link, verifies the URL changed to the /about page, and checks that an h1 element contains the text 'About': ```ts import { test, expect } from '@playwright/test' test('should navigate to the about page', async ({ page }) => { await page.goto('http://localhost:3000/') await page.click('text=About') await expect(page).toHaveURL('http://localhost:3000/about') await expect(page.locator('h1')).toContainText('About') }) ```

Playwright baseURL configuration

You can set a baseURL in playwright.config.ts to simplify test URLs. When baseURL is configured (e.g., "baseURL": "http://localhost:3000"), you can use page.goto("/") instead of page.goto("http://localhost:3000/") in your tests.

Running Playwright tests with production build

To run Playwright tests against production code, first run npm run build and npm run start to build and start the Next.js server. Then run npx playwright test in another terminal window to execute the Playwright tests. This approach more closely resembles how the application will behave in production.

Playwright webServer feature for automatic server startup

Playwright provides a webServer feature in its configuration that allows Playwright to automatically start the development server and wait until it is fully available before running tests, eliminating the need to manually start the server.

Playwright browser coverage

Playwright simulates a user navigating the application using three browsers: Chromium, Firefox, and WebKit. Tests run against all three browsers by default.

Playwright CI setup and headless mode

Playwright runs tests in headless mode by default on Continuous Integration systems. To install all Playwright dependencies required for CI environments, run npx playwright install-deps.

Test file naming and location conventions

Test files can follow the common __tests__ directory convention, or be colocated inside the app router directory.

Async Server Components not supported in Vitest unit tests

Vitest currently does not support async Server Components for unit testing. While you can still run unit tests for synchronous Server and Client Components, E2E tests are recommended for async components.

Vitest and React Testing Library for unit testing

Vitest and React Testing Library are frequently used together for Unit Testing in Next.js projects.

Vitest quickstart with create-next-app

Run 'create-next-app --example with-vitest' to quickly set up Vitest with Next.js using the with-vitest example template.

Vitest manual setup dependencies JavaScript

To manually set up Vitest with JavaScript, install these packages as dev dependencies: vitest, @vitejs/plugin-react, jsdom, @testing-library/react, and @testing-library/dom.

vitest.config.mts configuration file TypeScript

Create a vitest.config.mts file at the project root. Import defineConfig from 'vitest/config', react from '@vitejs/plugin-react', and tsconfigPaths from 'vite-tsconfig-paths'. Export a config with plugins: [tsconfigPaths(), react()] and test: { environment: 'jsdom' }.

vitest.config.js configuration file JavaScript

Create a vitest.config.js file at the project root. Import defineConfig from 'vitest/config' and react from '@vitejs/plugin-react'. Export a config with plugins: [react()] and test: { environment: 'jsdom' }.

Add test script to package.json

Add a test script to package.json with value 'vitest'. Running 'npm run test' will start Vitest in watch mode by default.

Vitest watch mode default

When you run the test script, Vitest watches for changes in your project by default.

Example Vitest unit test for Page component

Example test in __tests__/page.test.tsx: import { expect, test } from 'vitest' import { render, screen } from '@testing-library/react' import Page from '../app/page' test('Page', () => { render(<Page />) expect(screen.getByRole('heading', { level: 1, name: 'Home' })).toBeDefined() }) This test renders the Page component and verifies that a level 1 heading with text 'Home' is rendered.

Give your agent this brain