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
<Nav isMenuOpen>ornav().setState({ isMenuOpen: true }), which sets the props for theaside? 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.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.