React Component Tests for Humans
Crafting effective React component tests should be intuitive, straightforward, and easily maintainable. However, current testing library ecosystems often fall short, hindering developers from consistently writing robust JavaScript tests. Testing React components and the DOM frequently requires higher-level wrappers around popular test runners like Jest or Mocha.
The Challenge: Tedious and Confusing Testing
Current testing methods often prove tedious and confusing. The jQuery-like chaining style for expressing test logic is cumbersome and doesn't align with React's component architecture. Even seemingly readable code, like that using Enzyme, can become overly verbose:
expect(screen.find(".view").hasClass("technologies")).to.equal(true); expect(screen.find("h3").text()).toEqual("Technologies:"); expect(screen.find("ul").children()).to.have.lengthOf(4); expect(screen.contains([ // ... ])).to.equal(true); expect(screen.find("button").text()).toEqual("Back"); expect(screen.find("button").hasClass("small")).to.equal(true);
This corresponds to a relatively simple DOM structure:
<div classname="view technologies"> <h3 id="Technologies">Technologies:</h3> <ul> <li>JavaScript</li> <li>ReactJs</li> <li>NodeJs</li> <li>Webpack</li> </ul> <button classname="small">Back</button> </div>
Testing more complex components amplifies these issues, making the process even more unwieldy. The disconnect between React's principles for generating HTML and the testing approach leads to inefficient and difficult-to-maintain tests. Simple JavaScript chaining is insufficient for long-term maintainability.
Two key problems emerge:
- Component-Specific Testing Approach: How to effectively write tests tailored to component behavior.
- Minimizing Redundancy: How to eliminate unnecessary code and improve test readability.
Let's address these before exploring practical solutions.
A Focused Approach to React Component Testing
Consider a basic React component:
function Welcome(props) { return <h1 id="Hello-props-name">Hello, {props.name}</h1>; }
This function accepts props
and returns a DOM node using JSX. Since components are essentially functions, testing them involves verifying function behavior: how arguments affect the returned result. For React components, this translates to setting up props
and validating the rendered DOM. User interactions (clicks, mouseovers, etc.) that modify the UI also need to be programmatically triggered.
Enhancing Test Readability: The Arrange-Act-Assert Pattern
Clear, readable tests are crucial. This is achieved by concise wording and consistent structure. The Arrange-Act-Assert (AAA) pattern is ideal:
- Arrange: Prepare component props.
- Act: Render the component and trigger user interactions.
- Assert: Verify expected outcomes based on the component's markup.
Example:
it("should click a large button", () => { // Arrange props.size = "large"; // Act const component = mount(Send); simulate(component, { type: "click" }); // Assert expect(component, "to have class", "clicked"); });
For simpler tests, phases can be combined:
it("should render with custom text", () => { expect(Send, "when mounted", "to have text", "Send"); });
Improving Current Testing Practices
The previous examples, while conceptually sound, are not easily achievable with standard tools. Consider this more common approach:
it("should display the technologies view", () => { const container = document.createElement("div"); document.body.appendChild(container); act(() => { ReactDOM.render(<profilecard></profilecard>, container); }); const button = container.querySelector("button"); act(() => { button.dispatchEvent(new window.MouseEvent("click", { bubbles: true })); }); const details = container.querySelector(".details"); expect(details.classList.contains("technologies")).toBe(true); });
Compare this to a more abstract version:
it("should display the technologies view", () => { const component = mount(<profilecard></profilecard>); simulate(component, { type: "click", target: "button" }); expect(component, "queried for test id", "details", "to have class", "technologies"); });
This is cleaner and more readable. This level of abstraction is achievable with UnexpectedJS.
Testing with UnexpectedJS
UnexpectedJS is an extensible assertion library compatible with various test frameworks. Its plugin system and syntax simplify React component testing. We'll focus on usage and examples rather than delving deeply into UnexpectedJS's inner workings.
Example: A Profile Card Component
We'll test a ProfileCard
component (code omitted for brevity, but available in the referenced GitHub repository).
Setting Up the Project
To follow along, clone the GitHub repository and follow the instructions to set up the project and run the tests.
Component Tests
The tests (in src/components/ProfileCard/ProfileCard.test.js
) utilize the AAA pattern:
-
Prop Setup:
beforeEach
sets up default props.
beforeEach(() => { props = { data: { name: "Justin Case", posts: 45, creationDate: "01.01.2021", }, }; });
-
Specific Test Cases: Examples include testing for the "online" icon, bio text, the technologies view (with and without data), location display, callback function execution, and rendering with default props. Each test case clearly demonstrates the Arrange-Act-Assert pattern. (Detailed test cases omitted for brevity, but available in the GitHub repo).
-
Running Tests: All tests are executed with
yarn test
.
Conclusion
This example showcases a more effective approach to React component testing. By viewing components as functions and employing the AAA pattern, you can create more maintainable and readable tests. The choice of testing library should be guided by its ability to handle component rendering and DOM comparisons effectively; UnexpectedJS is a strong contender in this regard. Explore the provided GitHub repository for a complete understanding and further experimentation.
The above is the detailed content of React Component Tests for Humans. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

It's out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That's like this.

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

I'd say "website" fits better than "mobile app" but I like this framing from Max Lynch:

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...
