0

I am trying to test my NavComponent and following this guide https://medium.freecodecamp.org/the-right-way-to-test-react-components-548a4736ab22 but due to having <Link /> components nested in it, I am required to mount my NavComponent wrapped in a router like so:

import React from "react";
import { mount } from "enzyme";
import { StaticRouter } from 'react-router'
import Nav from './Nav';

describe("Nav", () => {
  let props;
  let mountedNav;

    const nav = () => {
      if (!mountedNav) {
        mountedNav = mount(
            <StaticRouter location="/">
            <Nav />
          </StaticRouter>
        );
      }
      return mountedNav;
    }

    beforeEach(() => {
    props = {
      isMenuOpen: false
    };
    mountedNav = undefined;
  });

  // All tests go here


});

When calling beforeEach() I want to set the props of my <Nav /> not for the wrapped router component.

I am unable to setProps on child elements via enzyme like so:

nav().find('aside').setProps({isMenuOpen: false})

as I will get the following error:

ReactWrapper::setProps() can only be called on the root
4
  • I am a bit confused about what you are trying to do. Can't you just do <Nav isMenuOpen> or nav().setState({ isMenuOpen: true }), which sets the props for the aside? Also, I recommend you use shallow rendering for your tests and create bunch of smaller tests that shallow render. This will give you a better isolation in tests and provide better test coverage. Commented Jan 30, 2018 at 13:13
  • Will update to use shallow, thanks. Yes you're correct, I could set the prop in my JSX but how do I update that prop in my test? I need it to change from false to true. Commented Jan 30, 2018 at 13:30
  • 1
    If you do use shallow, you can get rid of StaticRouter and then just use nav().setProps({ isMenuOpen: false });. Don't try to change props of DOM elements because that's not the React way of doing things in general. Make your React component props be responsible for DOM elements. This way you only work on React level and test for DOM changes. Commented Jan 30, 2018 at 13:42
  • Thanks Gasim. That is a great solution. I was also forgetting to pass the props to the Nav component Commented Jan 30, 2018 at 13:49

1 Answer 1

1

I needed to pass the props generated in the beforeEach() to <Nav> component.

const nav = () => {
  if (!mountedNav) {
    mountedNav = mount(
        <StaticRouter location="/">
        <Nav {...props} />
      </StaticRouter>
    );
  }
  return mountedNav;
}
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.