0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.jsとReact Testing LibraryでContextを使用しているコンポーネントのテストコードを書く方法

Posted at

下記のようなSampleContextというContextと、SampleContextを使用しているSampleというコンポーネントがあるとします。

SampleContext.tsx
"use client";

import React, { ReactNode, SetStateAction, useState } from "react";
import { Dispatch } from "react";

type Sample = {
  num: number;
  setNum: Dispatch<SetStateAction<number>>;
};

export const SampleContext = React.createContext({} as Sample);

export const SampleProvider = ({ children }: { children: ReactNode }) => {
  const [num, setNum] = useState<number>(0);

  return (
    <SampleContext.Provider value={{ num, setNum }}>
      {children}
    </SampleContext.Provider>
  );
};
Sample.tsx
"use client";

import { SampleContext } from "@/provider/SampleContext";
import { useContext, useState } from "react";

const Sample = () => {
  const { num, setNum } = useContext(SampleContext);
  const [inputNum, setInputNum] = useState<number>(0);

  return (
    <>
      <div>{num === 0 ? "0です" : "0以外です"}</div>
      <div>
        <input
          type="text"
          value={inputNum}
          onChange={(e) => setInputNum(Number(e.target.value))}
        />
      </div>
      <div>
        <button onClick={() => setNum(inputNum)}>更新</button>
      </div>
    </>
  );
};

export default Sample;

上記Sampleコンポーネントで「0です」と表示されるケースと「0以外です」と表示されるケースのテストコードをReact Testing Libraryで書こうとして、どうやって書くか悩みましたが下記のようにしたらできました。

Sample.test.tsx
import "@testing-library/jest-dom";
import Sample from "@/components/Sample";
import { render, screen } from "@testing-library/react";
import { SampleContext } from "@/provider/SampleContext";

describe("Sample", () => {
  it("numが0の場合、「0です」と表示されること", () => {
    render(
      <SampleContext.Provider value={{ num: 0, setNum: jest.fn() }}>
        <Sample />
      </SampleContext.Provider>
    );

    expect(screen.getByText("0です")).toBeInTheDocument();
  });

  it("numが0以外の場合、「0以外です」と表示されること", () => {
    render(
      <SampleContext.Provider value={{ num: 1, setNum: jest.fn() }}>
        <Sample />
      </SampleContext.Provider>
    );

    expect(screen.getByText("0以外です")).toBeInTheDocument();
  });
});
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?