React-router: How to test redirection with withRouter HoC (2.4) ?

Created on 18 May 2016  Â·  4Comments  Â·  Source: ReactTraining/react-router

Version

2.4.0

Hi,
I have a basic component connected with the new withRouter HoC.

const Authentication = React.createClass({

  componentDidMount(){
    (...)
    this.props.router.push('/login');
  },

  render() {
    return null;
  }
});

export default withRouter(Authentication);

How can i test the redirection that happend in the componentDidMount method ?
In my Jasmine test, i import my connected component but this.props.router is undefined.
Any ideas ? I can't find documentation about tests using withRouter HoC.

Most helpful comment

I was looking for the answer for this too and stumbled across here. You can actually pass router in as a prop, in your tests. You just need to mock the router object. We have something like this:

export const routerStub = () => ({
  push:              sinon.spy(),
  replace:           sinon.spy(),
  go:                sinon.spy(),
  goBack:            sinon.spy(),
  goForward:         sinon.spy(),
  setRouteLeaveHook: sinon.spy(),
  isActive:          sinon.spy(),
});

All 4 comments

You should not be redirecting there – use an onEnter hook to redirect.

I was looking for the answer for this too and stumbled across here. You can actually pass router in as a prop, in your tests. You just need to mock the router object. We have something like this:

export const routerStub = () => ({
  push:              sinon.spy(),
  replace:           sinon.spy(),
  go:                sinon.spy(),
  goBack:            sinon.spy(),
  goForward:         sinon.spy(),
  setRouteLeaveHook: sinon.spy(),
  isActive:          sinon.spy(),
});

@romaindso Hi, How to solve this problem?

Hi @swustzl
As @Munksey said, you can mock the router and his key to test your component.

With Jasmine it will be something like that:

describe('YourComponentWrappedWithRouter, () => {
  it('should call push method', () => {
    const routerMock = {
      push: jasmine.createSpy(),
      replace: jasmine.createSpy(),
      go:  jasmine.createSpy(),
      goBack: jasmine.createSpy(),
      goForward: jasmine.createSpy(),
      setRouteLeaveHook: jasmine.createSpy(),
      isActive: jasmine.createSpy()
    };
    wrapper.mount(<Authentication router={routerMock }/>);
    expect(routerMock.push).toHaveBeenCalled();
  });
}');

If you use jest, replace jasmine.createSpy() by jest.fn()

Was this page helpful?
0 / 5 - 0 ratings

Related issues

hgezim picture hgezim  Â·  3Comments

misterwilliam picture misterwilliam  Â·  3Comments

tomatau picture tomatau  Â·  3Comments

stnwk picture stnwk  Â·  3Comments

yormi picture yormi  Â·  3Comments