Reputation: 2068
I am using enzyme. I need to test a component that has react router Link as a child. I need the following
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
Upvotes: 4
Views: 1349
Reputation: 2785
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);
Upvotes: 1