Table of Contents
The Challenge: Tedious and Confusing Testing
Technologies:
A Focused Approach to React Component Testing
Hello, {props.name}
Enhancing Test Readability: The Arrange-Act-Assert Pattern
Improving Current Testing Practices
Testing with UnexpectedJS
Example: A Profile Card Component
Setting Up the Project
Component Tests
Conclusion
Home Web Front-end CSS Tutorial React Component Tests for Humans

React Component Tests for Humans

Mar 27, 2025 am 11:48 AM

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);
Copy after login

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>
Copy after login

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>;
}
Copy after login

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:

  1. Arrange: Prepare component props.
  2. Act: Render the component and trigger user interactions.
  3. 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");
});
Copy after login

For simpler tests, phases can be combined:

it("should render with custom text", () => {
  expect(Send, "when mounted", "to have text", "Send");
});
Copy after login

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);
});
Copy after login

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");
});
Copy after login

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:

  1. Prop Setup: beforeEach sets up default props.
beforeEach(() => {
  props = {
    data: {
      name: "Justin Case",
      posts: 45,
      creationDate: "01.01.2021",
    },
  };
});
Copy after login
  1. 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).

  2. 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It&#039;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.

Building an Ethereum app using Redwood.js and Fauna Building an Ethereum app using Redwood.js and Fauna Mar 28, 2025 am 09:18 AM

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

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

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&#039;s like this.

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

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.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

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

Using Markdown and Localization in the WordPress Block Editor Using Markdown and Localization in the WordPress Block Editor Apr 02, 2025 am 04:27 AM

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

Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

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...

See all articles