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.
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()
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: