JSPM

  • Created
  • Published
  • Downloads 7666
  • Score
    100M100P100Q126849F
  • License ISC

Enable DOM integration testing on Next.js pages

Package Exports

  • next-page-tester

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (next-page-tester) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Next page tester

Build status Test coverage report Npm version

The missing DOM integration testing tool for Next.js.

Given a Next.js route, this library will render the matching page in JSDOM, provided with the expected props derived from Next.js' routing system and data fetching methods.

import { getPage } from 'next-page-tester';
import { screen, fireEvent } from '@testing-library/react';

describe('Blog page', () => {
  it('renders blog page', async () => {
    const { render } = await getPage({
      route: '/blog/1',
    });

    render();
    expect(screen.getByText('Blog')).toBeInTheDocument();

    fireEvent.click(screen.getByText('Link'));
    await screen.findByText('Linked page');
  });
});

What

The idea behind this library is to reproduce as closely as possible the way Next.js works without spinning up servers, and render the output in a local JSDOM environment.

In order to provide a valuable testing experience next-page-tester replicates the rendering flow of an actual next.js application:

  1. fetch data for a given route
  2. render the server-side rendered result to JSDOM as plain html (including head element)
  3. mount/hydrate the client application to the previously rendered html

The mounted application is interactive and can be tested with any DOM testing library (like @testing-library/react).

next-page-tester will take care of:

  • loading and execute modules in the expected browser or server environments
  • resolving provided routes into matching page component
  • calling Next.js data fetching methods (getServerSideProps, getInitialProps or getStaticProps) if the case
  • wrapping page with custom _app and _document components
  • emulating client side navigation via Link, router.push, router.replace
  • handling pages' redirect returns
  • supporting next/router, next/head, next/link, next/config and environment variables

API

getPage

getPage accepts an option object and returns 4 values:

import { getPage } from 'next-page-tester';

const { render, serverRender, serverRenderToString, page } = await getPage({
  options,
});

render()

Type: () => { nextRoot: HTMLElement<NextRoot> }
Returns: #__next root element element.

Unless you have an advanced use-case, you should mostly use this method. Under the hood it calls serverRender() and then mounts/hydrates the React application into JSDOM #__next root element. This is what users would get/see when they visit a page.

serverRender()

Type: () => { nextRoot: HTMLElement<NextRoot> }
Returns: #__next root element element.

Inject the output of server side rendering into the DOM but doesn't mount React. Use it to test how Next.js renders in the following scenarios:

  • before Reacts mounts
  • when JS is disabled
  • SEO tests

serverRenderToString()

Type: () => { html: string }

Render the output of server side rendering as HTML string. This is a pure method without side-effects.

page

Type: React.ReactElement<AppElement>

React element of the application.

Options

Property Description type Default
route (mandatory) Next route (must start with /) string -
req Enhance default mocked request object req => req -
res Enhance default mocked response object res => res -
router Enhance default mocked Next router object router => router -
useApp Render custom App component boolean true
useDocument (experimental) Render Document component boolean false
nextRoot Absolute path to Next.js root folder string auto detected
nonIsolatedModules Array of modules that should use the same module instance in server and client environment string[] -
dotenvFile Relative path to a .env file holding environment variables string -
wrapper Map of render functions. Useful to decorate component tree with mocked providers. { Page?: NextPage => NextPage } -

Set up your test environment

Since Next.js is not designed to run in a JSDOM environment we need to setup the default JSDOM to allow a smoother testing experience:

  • Provide a window.scrollTo mock
  • Provide a IntersectionObserver mock
  • Cleanup DOM after each test

Run initTestHelpers in your global tests setup (in case of Jest It is setupFilesAfterEnv file):

import { initTestHelpers } from 'next-page-tester';
initTestHelpers();

Optional: patch Jest

Until Jest v27 is published, you might need to patch jest in order to load modules with proper server/client environments. Don't do this until you actually encounter issues.

  1. Install patch-package and follow its setup instructions
  2. Manually update node_modules/jest-runtime/build/index.js file and replicate this commit
  3. Run npx patch-package jest-runtime or yarn patch-package jest-runtime

Examples

Under examples folder we're documenting the testing cases which next-page-tester enables.

Notes

  • Data fetching methods' context req and res objects are mocked with node-mocks-http
  • Next page tester is designed to be used with any testing framework/library but It's currently only tested with Jest and Testing Library. Feel free to open an issue if you had troubles with different setups
  • It might be necessary to install @types/react-dom and @types/webpack when using Typescript in strict mode due to this bug

Experimental useDocument option

useDocument option is partially implemented and might be unstable.

Next.js versions support

next-page-tester focuses on supporting only the last major version of Next.js:

next-page-tester next.js
v0.1.0 - v0.7.0 v9.X.X
v0.8.0 + v10.X.X

FAQ

How do I make cookies available in Next.js data fetching methods?

You can set cookies by appending them to document.cookie before calling getPage. next-page-tester will propagate cookies to ctx.req.headers.cookie so they will be available to data fetching methods. This also applies to subsequent fetching methods calls triggered by client side navigation.

test('authenticated page', async () => {
  document.cookie = 'SessionId=super=secret';
  document.cookie = 'SomeOtherCookie=SomeOtherValue';

  const { render } = await getPage({
    route: '/authenticated',
  });
  render();
});

Note: document.cookie does not get cleaned up automatically. You'll have to clear it manually after each test to keep everything in isolation.

Error: Not implemented: window.scrollTo

Next.js Link component invokes window.scrollTo on click which is not implemented in JSDOM environment. In order to fix the error you should set up your test environment or provide your own window.scrollTo mock.

Warning: Text content did not match. Server: "x" Client: "y" error

This warning means that your page renders differently between server and browser. This can be an expected behavior or signal a bug in your code.

The same error could also be triggered when you import modules that, in order to work, need to preserve module identity throughout the entire SSR cycle (from the moment they are imported to SSR rendering): e.g. React.Context or css-in-js libraries. In this case you can list these modules in nonIsolatedModules option to preserve their identity: see styletron-react example.

Todo's

  • Consider reusing Next.js code parts (not only types)
  • Consider supporting Next.js trailingSlash option
  • Render custom _error page
  • Provide a debug option to log execution info

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Andrea Carraro

πŸ’» πŸš‡ ⚠️ 🚧

Matej Ε nuderl

πŸ’» πŸš‡ ⚠️ πŸ‘€ πŸ€” πŸ“–

Jason Williams

πŸ€”

arelaxend

πŸ›

kfazinic

πŸ›

Tomasz Rondio

πŸ›

Alexander Mendes

πŸ’»

Jan Sepke

πŸ›

DavidOrchard

πŸ›

This project follows the all-contributors specification. Contributions of any kind welcome!