react-router-testing-utils

A collection of utilities to test React Router with React Testing Library (Work in progress 🚧)

MIT License

Stars
35

Table of Contents

Installation

This module should be installed as one of your project's devDependencies:

With NPM

npm install --save-dev react-router-testing-utils

or

With yarn package manager

yarn add --dev react-router-testing-utils

Setup

Import react-router-testing-utils/extend-expect in your tests setup file, in order to extend Jest expectations:

// In your own jest-setup.js (or any other name)
import 'react-router-testing-utils/extend-expect'

// In jest.config.js add (if you haven't already)
setupFilesAfterEnv: ['<rootDir>/jest-setup.js']

With TypeScript

If you're using TypeScript, make sure your setup file is a .ts and not a .js to include the necessary types.

You will also need to include your setup file in your tsconfig.json if you haven't already:

  // In tsconfig.json
  "include": [
    ...
    "./jest-setup.ts"
  ],

Render in Router

This allows you to render a given component in a Router for un-browser environments

renderInRouter(ExampleAppRoutes, {
   initialEntries: ['/about']
})

expect(screen.getByTestId('example-about-page')).toBeVisible()

Custom matchers

toHaveQueryParam

This allows you to check if a location search has a certain query param value.

A query param is contained in a location search if all the following conditions are met:

  • It's name is contained in the location search
  • It's value is contained in the location search
  • It's given type corresponds to it's decoded value

In order to encode/decode query params, it's necessary to provide the param type from ParamTypes exported module

Examples

import { ParamTypes } from 'react-router-testing-utils'

const { history } = renderInRouter(ExampleAppRoutes, {
   shouldCheckHistory: true,
})

expect(history?.location.search).toHaveQueryParam({
   name: 'filter-object',
   type: ParamTypes.ObjectParam,
   value: { foo: 'foo' }
})

LICENSE

MIT

Badges
Extracted from project README
Build Status version MIT License All Contributors Watch on GitHub Star on GitHub Tweet