JSPM

  • Created
  • Published
  • Downloads 7795
  • Score
    100M100P100Q124111F
  • 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 return an instance of the matching page component instantiated with the properties derived by Next.js' routing system and server side data fetching.

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

describe('Blog page', () => {
  it('renders blog page', async () => {
    const Page = await getPage({
      route: '/blog/1',
      pagesDirectory: process.cwd() + '/src/pages',
    });

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

What

The idea behind this library is to enable integration tests on Next.js pages including server side data fetching and routing.

The testing approach suggested here consists of manually mocking external API's and get the component instance matching a given route.

Next page tester will take care of:

  • resolving provided routes into the matching page component
  • calling Next.js data fetching methods (getServerSideProps or getStaticProps) if the case
  • set up a mocked next/router provider initialized with the expected values (to test useRouter and withRouter)
  • instantiating the page component with the expected props

Options

Property Description type Default
route Next route (must start with /) - -
pagesDirectory Absolute path of Next's /pages folder - -
req Access default mocked request object
(getServerSideProps only)
res => res -
res Access default mocked response object
(getServerSideProps only)
req => req -
router Access default mocked Next router object router => router -

Notes

req and res objects are mocked with node-mocks-http.

Next page tester can be used with any testing framework/library.

It might be necessary to install @types/react-dom and @types/webpack when using Typescript in strict mode due to this bug.

Todo's

  • Make available dynamic api routes under /pages/api
  • Consider adding custom App and Document
  • Consider adding a getPage factory
  • Consider reusing Next.js code parts (not only types)