7

I have a simple component that uses react-router (I'm aware this is the alpha build):

{props.app && props.app.health &&
   <Match exactly pattern="/" component={HomeLogin} />
}

The docs recommending wrapping in <MemoryRouter /> to provide context to components while testing.

However, with Jest/Enzyme I'm not able to shallow() render - I have to use Enzyme's mount() or render(), which causes problems because HomeLogin is a connected component - I want to be able to test that my component renders the right thing, but not test the component rendered within it.

My test:

it('Renders based upon matched route', () => {
  let props = {
    app: { health: true },
  };
  const component = render(
    <Provider store={store}>
      <MemoryRouter location="/">
        <Jumbotron {...props} />
      </MemoryRouter>
    </Provider>
  );
  expect(toJson(component)).toMatchSnapshot();
});

How can I test the output of this component based upon the route without having to provide the redux store or using shallow render?

Update: If I try to use shallow() the snapshot renders no output.

1
  • 2
    Have you found the solution? Commented Jun 12, 2017 at 1:18

1 Answer 1

1

You can use .find(Jumbotron) and use that for matching as snapshot, for example:

const wrapped = component.find(Jumbotron);
expect(toJson(wrapped)).toMatchSnapshot();

I had a more complex example involving withRouter() and I was restoring to removing all keys from the output before matching as snapshot. Well, until testing for React-Router v4 gets more solid with Jest and snapshot testing. Example:

export function removeKeys(object) {
    if (object === undefined || object === null) {
        return object;
    }
    Object.keys(object).forEach((key) => {
        if (typeof object[key] === 'object') {
            removeKeys(object[key]);
        } else if (key === 'key') {
           delete object[key];
        }
    });
    return object;
}

...

expect(removeKeys(toJson(component))).toMatchSnapshot();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.