samedi 5 août 2017

How to test react-router Links with Enzyme?

I see quite a few similar questions to this, but all seem wildly outdated or incredibly convoluted.

I have a React component which contains a React Router Link component, like so:

export default class Home extends Component {                                      
  render() {                                                                       
    return (                                                                       
      <div className="Home">  
        <Link to="/mission">Begin</Link>                                           
      </div>                                              
    );                                                                             
  }                                                                                
}

Then, I am trying to test very simply that the Home component contains a Link component which has a to=/mission property, using Jest. So, as per the Testing React Router docs, I tried many variations of tests, but this code most succinctly demonstrates what I am trying to achieve (example uses jest-enzyme for brevity):

it('includes link to Mission scene', () => {                                       
  const home = shallow(<MemoryRouter><Home /></MemoryRouter>);                                                              
  expect(home).toContainReact(<Link to="/mission">Begin</Link>)                    
});

Obviously, that code has several issues, not the least of which is the error:

Warning: Failed context type: The context `router` is marked as required in `Link`, but its value is `undefined`.

But notice the key bits: I want to shallow render (if possible) the Home component in order to test that component in isolation. At the same time, I am trying to wrap that in a MemoryRouter or somehow get the context in place so that I can test the Link components.

Astute potential answerers will notice that this issue is actually going to prevent all isolated tests of that component (not just tests related to React Router), because I can't shallow render the component at all.

Aucun commentaire:

Enregistrer un commentaire