To set up Jest, install jest , @testing-library/react, @testing-library/jest-dom:

npm install --save-dev jest @testing-library/react @testing-library/jest-dom
You can use create-next-app with the with-jest example to quickly get started with Jest and React Testing Library:

npx create-next-app@latest --example with-jest with-jest-app
Similar to the act() helper from react-dom/test-utils, TestRenderer.act prepares a component for assertions. Use this version of act() to wrap calls to TestRenderer.create and testRenderer.update.

import {create, act} from 'react-test-renderer';
import App from './app.js'; // The component being tested

// render the component
let root; 
act(() => {
  root = create(<App value={1}/>)
});

// make assertions on root 
expect(root.toJSON()).toMatchSnapshot();

// update with some different props
act(() => {
  root.update(<App value={2}/>);
})

// make assertions on root 
expect(root.toJSON()).toMatchSnapshot();
You can pass createNodeMock function to TestRenderer.create as the option, which allows for custom mock refs. createNodeMock accepts the current element and should return a mock ref object. This is useful when you test a component that relies on refs.

import TestRenderer from 'react-test-renderer';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.input = null;
  }
  componentDidMount() {
    this.input.focus();
  }
  render() {
    return <input type="text" ref={el => this.input = el} />
  }
}

let focused = false;
TestRenderer.create(
  <MyComponent />,
  {
    createNodeMock: (element) => {
      if (element.type === 'input') {
        // mock a focus function
        return {
          focus: () => {
            focused = true;
          }
        };
      }
      return null;
    }
  }
);
expect(focused).toBe(true);
For example, we can add a test to check if the component successfully renders a heading:

// __tests__/index.test.jsx

import { render, screen } from '@testing-library/react'
import Home from '../pages/index'

describe('Home', () => {
  it('renders a heading', () => {
    render(<Home />)

    const heading = screen.getByRole('heading', {
      name: /welcome to next\.js!/i,
    })

    expect(heading).toBeInTheDocument()
  })
})
Here is how we can test it:

import React from 'react';
import ReactDOM from 'react-dom';
import { act } from 'react-dom/test-utils';import Counter from './Counter';

let container;

beforeEach(() => {
  container = document.createElement('div');
  document.body.appendChild(container);
});

afterEach(() => {
  document.body.removeChild(container);
  container = null;
});

it('can render and update a counter', () => {
  // Test first render and componentDidMount
  act(() => {    ReactDOM.render(<Counter />, container);  });  const button = container.querySelector('button');
  const label = container.querySelector('p');
  expect(label.textContent).toBe('You clicked 0 times');
  expect(document.title).toBe('You clicked 0 times');

  // Test second render and componentDidUpdate
  act(() => {    button.dispatchEvent(new MouseEvent('click', {bubbles: true}));  });  expect(label.textContent).toBe('You clicked 1 times');
  expect(document.title).toBe('You clicked 1 times');
});
Optionally, add a snapshot test to keep track of any unexpected changes to your component:

// __tests__/snapshot.js

import { render } from '@testing-library/react'
import Home from '../pages/index'

it('renders homepage unchanged', () => {
  const { container } = render(<Home />)
  expect(container).toMatchSnapshot()
})
- Rename src/server/render-app.js to src/server/render-app.jsx and edit it like so:

// @flow

import React from 'react'
import ReactDOMServer from 'react-dom/server'
import { Provider } from 'react-redux'
import { StaticRouter } from 'react-router'

import initStore from './init-store'
import App from './../shared/app'
import { APP_CONTAINER_CLASS, STATIC_PATH, WDS_PORT } from '../shared/config'
import { isProd } from '../shared/util'

const renderApp = (location: string, plainPartialState: ?Object, routerContext: ?Object = {}) => {
const store = initStore(plainPartialState)
const appHtml = ReactDOMServer.renderToString(
<Provider store={store}>
<StaticRouter location={location} context={routerContext}>
<App />
</StaticRouter>
</Provider>)

return (
`<!doctype html>
<html>
<head>
<title>FIX ME</title>
<link rel="stylesheet" href="${STATIC_PATH}/css/style.css">
</head>
<body>
<div class="${APP_CONTAINER_CLASS}">${appHtml}</div>
<script>
window.__PRELOADED_STATE__ = ${JSON.stringify(store.getState())}
</script>
<script src="${isProd ? STATIC_PATH : `http://localhost:${WDS_PORT}/dist`}/js/bundle.js"></script>
</body>
</html>`
)
}

export default renderApp
- Edit src/server/render-app.jsx like so:

import Helmet from 'react-helmet'
// [...]
const renderApp = (/* [...] */) => {
// [...]
const appHtml = ReactDOMServer.renderToString(/* [...] */)
const head = Helmet.rewind()

return (
`<!doctype html>
<html>
<head>
${head.title}
${head.meta}
<link rel="stylesheet" href="${STATIC_PATH}/css/style.css">
</head>
[...]
`
)
}
Render a React element into a detached DOM node in the document. This function requires a DOM. It is effectively equivalent to:

const domContainer = document.createElement('div');
ReactDOM.render(element, domContainer);

Recommend

Nextjs Testing Jest and React Testing Library Quickstart

Nextjs Testing Playwright Creating your first Playwright end-to-end test

Nextjs Testing Playwright Manual setup

Nextjs Testing Playwright Quickstart

Nextjs Testing Cypress Getting ready for Continuous Integration (CI)

Nextjs Testing Cypress Creating your first Cypress integration test

Nextjs Testing Cypress Manual setup

Nextjs Testing Cypress Quickstart

Nextjs Middleware Execution Order

Nextjs Middleware API

Nextjs Middleware Usage

Matplotlib Overview of axisartist toolkit FloatingAxis

Matplotlib Overview of axisartist toolkit GridHelper

Matplotlib Overview of axisartist toolkit Rotation and Alignment of TickLabels Adjusting pad

Matplotlib Overview of axisartist toolkit Rotation and Alignment of TickLabels

Matplotlib Overview of axisartist toolkit HowTo

Matplotlib Overview of axisartist toolkit Default AxisArtists

Matplotlib Overview of axisartist toolkit axisartist axisartist with ParasiteAxes

Matplotlib Overview of axisartist toolkit axisartist

Matplotlib The mplot3d Toolkit Tri-Surface plots

Matplotlib The mplot3d Toolkit

Matplotlib Overview of mpl_toolkits.axes_grid1 AxesDivider

Matplotlib Overview of mpl_toolkits.axes_grid1 axes_grid1 RGBAxes

Matplotlib Overview of mpl_toolkits.axes_grid1 axes_grid1 InsetLocator

Matplotlib Overview of mpl_toolkits.axes_grid1 axes_grid1 ParasiteAxes Example 2. twin

Matplotlib Overview of mpl_toolkits.axes_grid1 axes_grid1 colorbar whose height (or width) in sync with the master axes scatter_hist.py with AxesDivider

Matplotlib Overview of mpl_toolkits.axes_grid1 axes_grid1 AxesDivider Class

Matplotlib Image tutorial Plotting numpy arrays as images Array Interpolation schemes

Matplotlib Image tutorial Plotting numpy arrays as images Examining a specific data range

Matplotlib Image tutorial Plotting numpy arrays as images Color scale reference

Matplotlib Image tutorial Plotting numpy arrays as images Applying pseudocolor schemes to image plots

Matplotlib Image tutorial Plotting numpy arrays as images

Matplotlib Image tutorial Importing image data into Numpy arrays

Matplotlib Image tutorial Startup commands

Matplotlib Pyplot tutorial Logarithmic and other nonlinear axes

Matplotlib Pyplot tutorial Working with text Annotating text

Matplotlib Pyplot tutorial Working with text Using mathematical expressions in text

Matplotlib Pyplot tutorial Working with text

Matplotlib Pyplot tutorial Working with multiple figures and axes

Matplotlib Pyplot tutorial Controlling line properties

Matplotlib Pyplot tutorial Plotting with categorical variables

Matplotlib Pyplot tutorial Plotting with keyword strings

Matplotlib Pyplot tutorial Intro to pyplot Formatting the style of your plot

Matplotlib Pyplot tutorial Intro to pyplot

Matplotlib Basic Usage Working with multiple Figures and Axes

Matplotlib Basic Usage Color mapped data

Matplotlib Basic Usage Axis scales and ticks Additional Axis objects

Matplotlib Basic Usage Axis scales and ticks Plotting dates and strings