LoginSignup
0
1

More than 3 years have passed since last update.

【React】jestを使用したテスト

Last updated at Posted at 2021-04-16

書き方

import { unmountComponentAtNode } from "react-dom";
import { act } from 'react-dom/test-utils';

describe('テスト箇所', () => {
  let container = null;

  // セットアップ
  beforeEach(() => {
    // documentにDOM要素を描画する
    container = document.createElement('div');
    document.body.appendChild(container);
  });

  // クリーンアップ
  afterEach(() => {
    // documentからDOM要素を削除する
    unmountComponentAtNode(container);
    container.remove();
    container = null;
  });

  it('テスト内容', () => {
    act(() => {
      // コンポーネントをレンダリングする
    });

    // アサーション
    expect('test').toBe('test'); // コンポーネントのレンダリングが完了していることが保証されている
  });
});

unmountComponentAtNode()

  • DOMからマウントされたReactコンポーネントを削除する
  • イベントハンドラや state をクリーンアップする

act()

  • react-dom/test-utils が提供するテストのための関数
  • アサーションの前に act() 内の処理がすべて完了し、DOM に反映されていることを保証する
0
1
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
1