Catalog / Enzyme Testing Cheatsheet
Enzyme Testing Cheatsheet
A comprehensive cheat sheet for testing React components with Enzyme, covering essential methods, selectors, and best practices for effective testing.
Enzyme Basics & Setup
Installation
Install Enzyme and an adapter for your React version. For React 16, use
For React 17, use
|
Configuration
Configure Enzyme in your test setup file (e.g.,
Replace |
Mounting Components
|
Shallow renders only the top-level component, not its children. Useful for isolating unit tests.
|
|
Full DOM rendering, including child components. Requires a DOM environment (e.g., jsdom).
|
|
Renders to static HTML. Useful for testing the rendered output. Returns a Cheerio wrapper.
|
Selectors & Traversal
Finding Nodes
|
Finds all elements matching the CSS selector, component, or React element.
|
|
Finds elements based on a custom predicate function.
|
|
Filters the current selection of nodes based on the selector.
|
Traversal
|
Returns the direct children of the current node(s).
|
|
Returns the parent of the current node(s).
|
|
Returns the first ancestor matching the selector.
|
Simulating Events & Assertions
Simulating Events
|
Simulates an event on the selected node(s).
|
Common Events |
|
Assertions
|
Checks if elements matching the selector exist.
|
|
Returns the text content of the node(s).
|
|
Returns the HTML content of the node(s).
|
|
Returns all props of the root node.
|
|
Returns a specific prop of the root node.
|
State & Props
|
Gets the state of a stateful component. If
|
|
Sets the props of the component. Triggers a re-render. (Only for
|
|
Forces a re-render of the component. Useful when props or state have been updated indirectly.
|
Advanced Techniques
Testing Higher-Order Components (HOCs)
When testing HOCs, test the unwrapped component directly to isolate its logic.
|
Testing Connected Components (Redux)
When testing connected components, test the unconnected component directly and mock the Redux store.
|
Mocking Modules
Use Jest’s mocking capabilities to isolate components and control dependencies.
|