Skip to content

Mock hooks in RTL

Mock React Hook with different value in each test case

React
Form.test.tsx
import '@testing-library/jest-dom';
 
import {render} from '@testing-library/react';
import React from 'react';
 
import {Form} from './Form';
import * as useInputFormHook from './useInputForm';
 
jest.mock('./useInputForm', () => ({
  useInputForm: jest.fn(),
}));
 
describe('Form', () => {
  it('should do disable controls on submit', () => {
    // Spy and set the return value of the mock
    jest.spyOn(useInputFormHook, 'useInputForm').mockImplementation(() => ({
      state: 'DISABLED',
      onSubmit: jest.fn(),
    }));
 
    const {getByTestId} = render(<Form />);
    const submitButton = getByTestId('submit-button');
 
    expect(submitButton).toBeDisabled();
  });
 
  it('should show error message on validation error', () => {
    // Spy and set the return value of the mock
    jest.spyOn(useInputFormHook, 'useInputForm').mockImplementation(() => ({
      state: 'INVALID',
      onSubmit: jest.fn(),
    }));
 
    const {getByTestId} = render(<Form />);
    const errorMessage = getByTestId('input-error');
 
    expect(errorMessage).toBeInTheDocument();
  });
});