search
HomeWeb Front-endCSS TutorialReact Component Tests for Humans

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:

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

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:

  1. Prop Setup: beforeEach sets up default props.
beforeEach(() => {
  props = {
    data: {
      name: "Justin Case",
      posts: 45,
      creationDate: "01.01.2021",
    },
  };
});
  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
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
The Ultimate Guide to Linking CSS Files in HTMLThe Ultimate Guide to Linking CSS Files in HTMLMay 13, 2025 am 12:02 AM

Linking CSS files to HTML can be achieved by using elements in part of HTML. 1) Use tags to link local CSS files. 2) Multiple CSS files can be implemented by adding multiple tags. 3) External CSS files use absolute URL links, such as. 4) Ensure the correct use of file paths and CSS file loading order, and optimize performance can use CSS preprocessor to merge files.

CSS Flexbox vs Grid: a comprehensive reviewCSS Flexbox vs Grid: a comprehensive reviewMay 12, 2025 am 12:01 AM

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

How to Include CSS Files: Methods and Best PracticesHow to Include CSS Files: Methods and Best PracticesMay 11, 2025 am 12:02 AM

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

See all articles

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 Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),