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 1 year has passed since last update.

react-hook-formでyupResolverを使った時のmock化をちゃんとやる

Last updated at Posted at 2024-02-14

背景

react-hook-formのuseFormでresolverにyupResolverを使っている。

jestのカバレッジのStmtsが低い

テストパターンを網羅しているつもりなのにStmtsが100%にならない
スクリーンショット 2024-02-14 18.28.23.png

yupResolverもモック化して解決

hook側のuseFormの記述

react.js
export const schema = object({
  password: string().required('パスワードを入力してください').min(6, '6文字以上で入力してください'),
});
react.js
const {
    register,
    getValues,
    formState: { errors, isValid },
    handleSubmit,
    reset,
  } = useForm<{ password?: string }>({
    defaultValues: { password: undefined },
    resolver: yupResolver(schema),
    mode: 'onChange',
  });

jestのテスト

react.js
import { yupResolver } from '@hookform/resolvers/yup';
import { useForm } from 'react-hook-form';

jest.mock('react-hook-form');
jest.mock('@hookform/resolvers/yup');

describe('useTest', () => {
  const mockYupResolver = yupResolver as jest.Mock;
  beforeEach(() => {
    mockYupResolver.mockImplementation(() => {});
    (useForm as jest.Mock).mockReturnValue({
      register: jest.fn(),
      getValues: mockGetValues,
      formState: { errors: {}, isValid: true },
      handleSubmit: jest.fn(),
      reset: mockReset,
    });
  });

  it('should exec yupResolver', () => {
    const { result } = renderHook(() => useTest());
    // yupResolverが1回呼ばれていることを確認
    expect(mockYupResolver).toHaveBeenCalledTimes(1);
    // yupResolverがschemaを引数にしていることを確認
    expect(mockYupResolver).toHaveBeenCalledWith(schema);
  });
});

最後に

カバレッジが100%になってスッキリ!

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?