Unit and integration testing

DEMO
Crowdfunder.jsx

Post.jsx
ProgressStats.jsx
BackProject.jsx
const Crowdfunder = () => {
  const { data, error } = useSWR("/api/crowdfunder", fetcher);

  return (
    <DemoWrapper>
      {data ? (
        <Post {...data} />
      ) : (
        <SkeletonPost/>
      )}
    </DemoWrapper>
  );
};

export default Crowdfunder;
Writing unit and integrations tests are important to catch bugs and increase confidence in the application.
With React Testing Library, avoid including implementation details of the component e.g. state. Instead, test for changes in the UI.
Post.test.js

ProgressStats.test.js
BackingProject.test.js
Crowdfunder.test.js
// Roles: https://www.w3.org/TR/html-aria/#docconformance
import { fireEvent, render, screen } from "@testing-library/react";
import Crowdfunder from "../Crowdfunder";
import BackProject from "../BackProject";
import ProgressStats from "../ProgressStats";
import Post from "../Post";
import img from "../../../images/genieLamp.jpg";

const postProps = {
  title: "Mini Yggdrasil",
  content: "A miniature plant based on the world tree",
  raisedSoFar: 300,
  target: 1000,
  img: img,
};

describe("Post", () => {
  it("renders crowdfunder post details", () => {
    render(<Post {...postProps} />);
    const title = screen.getByRole("heading", { name: "Mini Yggdrasil" });
    const content = screen.getByText(
      "A miniature plant based on the world tree"
    );
    const image = screen.getByRole("img");
    expect(title).toBeInTheDocument();
    expect(content).toBeInTheDocument();
    expect(image).toBeInTheDocument();
    expect(image).toHaveAttribute("src", img);
  });

});
Notice in Crowdfunder.test.js that we mock the server using theMock Service Workerlibrary. Using our actual API is not ideal as requests are slow, costly and can be unreliable since errors may not come from the frontend.

Note: Code snippets do not include styling details unless they are the focus of the exercise.

Copyright © 2022 Explore React