4
votes

I am using enzyme. I need to test a component that has react router Link as a child. I need the following

  • mount the component using mount() of enzyme since I need to test the whole component tree
  • test behaviours of component when it properties change.

I cannot wrap my component with StaticRouter or MemoryRouter since enzyme only allows setProps() at root level.

My current solution is to stub the Link render method with sinon. Here is a short example.

import {Link} from 'react-router-dom';
import sinon from 'sinon';

// ....
// ....

describe('test',() => {
   before(() => {
      sinon.stub(Link.prototype, 'render').callsFake(function reactRouterLinkRender() {
           const {innerRef, replace, to } = this.props;
           const _props = {href: to, ref: innerRef, replace, onClick: this.handleClick};
           return (<a {..._props}>this.props.children</a>);
       });

    });
});

Is there a better way to avoid the error "Invariant Violation: You should not use Link outside a Router"?

Thanks

1
Please see my answer.It may help you. stackoverflow.com/a/52533139/5465023亚里士朱德

1 Answers

1
votes

Not sure if this helps anyone but for my case I managed to get around by shallow rendering the top level component and then using dive() to get to the parts I required.

loginPage = shallow(<LoginPage />);

....

loginPage.find(LoginForm).dive().find({name:"user"}).simulate("change", userEventMock);