1

tl/dr: How do I wait for an async componentDidMount, simulate a React Router redirect and test the resulting page?

I have a React component with a componentDidMount which asynchronously requests data from an API then sets state.

In my Enzyme/Mocha tests, I can wait for componentDidMount like this:

  it('should show an input with quantity 0 by default', async () => {
    const component = shallow(<ShowPage />);
    await component.instance().componentDidMount();
    component.update();
    expect(component.find('h1').text()).to.eq('Show page');
  });

This is fine, but I also want to test a button click which redirects the user to another page. This uses:

this.props.history.push('/redirect-to')

The history prop is not available unless I wrap the component in a MemoryRouter:

const component = mount(<MemoryRouter><ShowPage /></MemoryRouter>);

But now I can't access the ShowPage component's componentDidMount because:

await component.find('BurgerShow').instance().componentDidMount();

gets me:

instance() can only be called on the root

I feel like I'm making very heavy weather of this. What is the correct approach here?

LondonRob
  • 53,478
  • 30
  • 110
  • 152
  • I found [some advice](https://stackoverflow.com/a/50684599/2071807) suggesting mocking the `history.push`. Is this the right way to proceed? – LondonRob Dec 04 '18 at 18:42

0 Answers0