0

I am trying to create a unit test for a react component where the props to the component checks part of the url path to decide a course of action and at the end of the path takes in a parameter or value.

Using the example given in https://testing-library.com/docs/example-reach-router I created my own unit test but when I run the test my component complain that the uri value is not there. In addition, when I add a console.log(props) to my component and run the test again, props is undefined.

I have tried a variation of wrapping my component with LocationProvider adding in history as shown in https://reach.tech/router/api/LocationProvider

The relevant code snippet is -

function renderWithRouter(
  ui,
  { route = '/', history = createHistory(createMemorySource(route)) } = {}
) {
  return {
    ...render(

      <LocationProvider history={history}>{ui}</LocationProvider>
    )
    ,
    history,
  }
}

describe('View Order Test', () => {

  describe('Order', () => {

    it('Renders the Order View for a specific Order', async () => {

      const { queryByText } =
        renderWithRouter(

          <State initialState={initialState} reducer={reducer}>
            <ViewOrder />
          </State>
          , { route: '/order/orderView/1234', }
        )
      expect(queryByText('OrderID: 1234'))
    }
    )
  })

Nothing seems to work. Is there some way of passing props to a component which are uri (@reach/router) in a unit? As I said my unit is a carbon copy of the those given above

Community
  • 1
  • 1
Andy5
  • 2,319
  • 11
  • 45
  • 91

2 Answers2

0

Solved by adding Reach Router and wrapping it around the component.

Andy5
  • 2,319
  • 11
  • 45
  • 91
0

I had a similar problem when testing a component using url parameters with reach-router.

Route file example:

import { Router } from "@reach/router";
import Item from "pages/Item";

const Routes = () => (
  <Router>
    <Item path="/item/:id" />
  </Router>
);
...

In my testing code, I did this in render function:

import {
  Router,
  createHistory,
  createMemorySource,
  LocationProvider,
} from "@reach/router";
import { render } from "@testing-library/react";

export function renderWithRouter(
  ui,
  { route = "/", history = createHistory(createMemorySource(route)) } = {}
) {
  return {
    ...render(
      <LocationProvider history={history}>
        <Router>{ui}</Router>
      </LocationProvider>
    ),
    history,
  };
}

and the test case:

test("renders the component", async () => {
  renderWithRouter(<Item path="/item/:id" />, { route: "/item/1" });
  ...
});

In this way, I was able to get the url parameters and all tests worked well.

deadkff01
  • 41
  • 3