Resources:
- https://hackernoon.com/testing-react-components-with-jest-and-enzyme-41d592c174f
- https://jestjs.io/docs/en/snapshot-testing
- cheat sheet: https://github.com/sapegin/jest-cheat-sheet
- https://medium.com/codeclan/testing-react-with-jest-and-enzyme-20505fec4675
Why Enzyme?
- utilities work with shallow rendering, static rendering, or DOM
- API to find elements, read props
Important Jest matchers for snapshot testing:
.toMatchStanpshot()
will compare the snapshot to the rendered UI. A snapshot is created the first time the test file is run.jest -u
in the CLI will update a snapshot to the new changed UI..any()
will allow generated content within the snapshot to be anything. Pass in types to check against likeNumber
orBoolean
orDate
..simulate()
is used to simulate events such asclick
orhover
.find()
will take a CSS selector and locate an element in the rendered component.toHaveLength()
can be used creatively to find the number of children after an element is interacted with
Enzyme methods
mount()
- Ideal for use cases where you have components that may interact with DOM API, or use React lifecycle methods in order to fully test the component
- As it actually mounts the component in the DOM .unmount() should be called after each tests to stop tests affecting each other
- Allows access to both props directly passed into the root component (including default props) and props passed into child components
shallow()
- Renders only the single component, not including its children. This is useful to isolate the component for pure unit testing. It protects against changes or bugs in a child component altering the behaviour or output of the component under test
- As of Enzyme 3 shallow components do have access to lifecycle methods by default
- Cannot access props passed into the root component (therefore also not default props), but can those passed into child components, and can test the effect of props passed into the root component. This is as with shallow(), you're testing what MyComponent renders - not the element you passed into shallow
render()
- renders static HTML, including children
- does not have access to react lifecycle methods
- less costly than mount but provides less functionality