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!

The React ecosystem offers us a lot of libraries that all are focused on the interaction of drag and drop. We have react-dnd, react-beautiful-dnd,

There have been some wonderfully interconnected things about fast software lately.

I can't say I use background-clip all that often. I'd wager it's hardly ever used in day-to-day CSS work. But I was reminded of it in a post by Stefan Judis,

Animating with requestAnimationFrame should be easy, but if you haven’t read React’s documentation thoroughly then you will probably run into a few things

Perhaps the easiest way to offer that to the user is a link that targets an ID on the element. So like...

Listen, I am no GraphQL expert but I do enjoy working with it. The way it exposes data to me as a front-end developer is pretty cool. It's like a menu of

In this week's roundup, a handy bookmarklet for inspecting typography, using await to tinker with how JavaScript modules import one another, plus Facebook's

I've recently noticed an interesting change on CodePen: on hovering the pens on the homepage, there's a rectangle with rounded corners expanding in the back.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment