How do you test router match params with jest and enzyme? How do you test router match params with jest and enzyme? reactjs reactjs

How do you test router match params with jest and enzyme?


Use containsMatchingElement

const wrapper = shallow(  <Details    required={true}    match={{params: {id: 1}, isExact: true, path: "", url: ""}}  />);expect(wrapper.containsMatchingElement(<h2>Details for 1</h2>)).toBeTruthy();


Wrap All Tests In Context

Router exists in context, so you can wrap your tests in context and supply match params to it to test how your component picks them up.

import { BrowserRouter } from 'react-router-dom';import { shape } from 'prop-types';import { mount } from 'enzyme';// Instantiate router contextconst router = route => ({  history: new BrowserRouter().history,  route,});const createContext = route => ({  context: { ...router(route) },  childContextTypes: { router: shape({}) },});export function mountWrap(node, route) {  return mount(node, createContext(route));}

Example describe:

import React from 'react';import { TableC } from '../../src/tablec';import { mountWrap, shallowWrap } from '../testhelp/contextWrap';import { expectedProps } from './mockdata'describe('Table', () => {  let props;  let component;  let route = {    location: {},    match: {[MATCH OBJ HERE]}  }  const wrappedMount = () => mountWrap(<TableC {...props} />, route);  beforeEach(() => {    props = {      query: {        data: tableData,        refetch: jest.fn(),      },    };    if (component) component.unmount();  });  test('should call a DeepTable with correct props', () => {    let route = {      location: {},      match: {[UPDATE MATCH OBJ HERE BEFORE TEST]}    }    const wrapper = wrappedMount();    expect(wrapper.find('DeepTable').props()).toEqual(expectedProps);  });});

This also allows you to optionally add other things to context, and allows the top level object in the wrapper to be your component (as opposed to wrapping with BrowserRouter or StaticRouter)