React router - useOutletContext testing

Viewed 690

I'm using react-router V6 and trying to test the new feature of useOutletContext. my testing library is testing-library/react and I'm not sure how to pass the Context data in the test.

In the TSX component, I'm getting the data with the hook of react-router:

const { data } = useOutletContext<IContext>()

I need something like:

test("render outlet context data view", async () => {
  const { getByTestId } = render(
    <MockedProvider mocks={[mockData]} context={myContextData}>
       <ContextDataView />
    </MockedProvider>
)

the MockedProvider tag is from @apollo/client/testing

the context={myContextData} part is what i need

2 Answers

I needed the same thing at work, and one of my colleagues helped me finally figure it out.

in your test file

import * as rrd from 'react-router-dom';

then set up your data just like you'd expect, and use Jest to mock React-router-dom

let mockData = { mock: 'Data' }
jest.mock('react-router-dom');

and then in your test

test("render outlet context data view", async () => {
  rrd.useOutletContext.mockReturnValue(mockData)
  render(<ContextDataView />)
}

I performed the following to mock one of the objects on my Outlet Context:

Outlet defined in Layout.tsx:

<Outlet context={{myModel1, myModel2, myModel3}} />

Test class:

import { act, cleanup, render, screen } from '@testing-library/react';
import { IMyModel1 } from 'Models/IMyModel1';
import * as rrd from 'react-router-dom';

jest.mock('react-router-dom');
const mockedOutletContext = rrd as jest.Mocked<typeof rrd>;

afterEach(() => {
    cleanup;
    mockedOutletContext.Outlet.mockReset();
  });

Within your test, mock the object as required:

const myModel1: IMyModel1 = {};
const outletContext: rrd.OutletProps = { context: { myModel1: myModel1 } };
mockedOutletContext.useOutletContext.mockReturnValue(outletContext.context);
Related