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?

More than 3 years have passed since last update.

ReactのJestのテストでuseStateを使用する方法

Last updated at Posted at 2022-01-25

#背景

業務でReactのテストをJestで作成した際、HooksのuseStateでエラーになり、かなり悩んだのでその解決策をまとめておく。

#開発言語 (バージョン情報)

  • React.js (17.0.2)
  • Next.js (11.1.2)
  • TypeScript (4.4.3)
  • Jest (27.2.2)

#解決策

sample.spec.tsx
import React, { useState as useStateMock } from 'react';
import TestRender from 'react-test-renderer';

jest.mock('react', () => ({
 ...jest.requireActual('react'),
 useState: jest.fn(),
}));

describe('Snapshot test', () => {
  const setState = jest.fn();

  beforeEach(() => {
    (useStateMock as jest.Mock).mockImplementation(init => [init, setState]);
  });

  test('test case 1', () => {
    const [open, setOpen] = useStateMock(true);
    const tree = TestRenderer.create(
      <>
        {open}
        test
      </>,
    ).toJSON();
    expect(tree).toMatchSnapshot();
  });

});

#参考

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?