1

I am totally new in testing. Now I'm trying to test react routre. How to test it correctly? Register.js

import React from "react";
import { Redirect, Route, Switch } from "react-router-dom";

import user from "./user";
import employee from "./employee";

const Registers = ({ match }) => (
  <div className="dashboard-wrapper">
    <Switch>
      <Redirect exact from={`${match.url}/`} to={`${match.url}/user`} />
      <Route path={`${match.url}/user`} component={user} />
      <Route path={`${match.url}/employee`} component={employee} />
      <Redirect to="/error" />
    </Switch>
  </div>
);
export default Registers;

Tryed to test in this way.

   Enzyme.configure({ adapter: new Adapter() });
    test('invalid path should redirect to 404', () => {
    const wrapper = mount(
     <MemoryRouter initialEntries={[ '/user' ]}>
       <Registers/>
     </MemoryRouter>
   );
  expect(wrapper.find(user)).toHaveLength(0);
  expect(wrapper.find(employee)).toHaveLength(1);
});

1 Answer 1

0
  • First you need to wrap your Switch statement with Browser Router
  • Second You need To mock Browser Router.

Mock Browser Router at path

" __mocks__/react-router-dom.js "

import React from 'react';
const rrd = require('react-router-dom');
// Just render plain div with its children
rrd.BrowserRouter = ({children}) => <div>{children}</div>
module.exports = rrd;

Test like

test('invalid path should redirect to 404', () => {
  const wrapper = mount(
    <MemoryRouter initialEntries={[ '/user' ]}>
      <App/>
    </MemoryRouter>
  );
  expect(wrapper.find(user)).toHaveLength(0);
  expect(wrapper.find(employee)).toHaveLength(1);
});
Sign up to request clarification or add additional context in comments.

11 Comments

Can you explain how and why to Mock Browser Router, please. Didn't understand that part
I created a folder named react-router-dom.js and pass contend like you suggest. Now getting error. TypeError: Cannot read property 'url' of undefined Error throws here ` from={${match.url}/}` Solved by adding this in test. <Registers match={{url:""}}/> Is this correct solution?
i think in your test file you need to mock whatever you're testing. jest.mock()
Found article like your suggest. But can't understand jest.mock('firebase/app'); what is doing this. I think something like this I missed. medium.com/@antonybudianto/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.