To mock a returned function from a custom hook during testing using Jest and React Testing Library, you can use the jest.fn() method to create a mock function and then mock the custom hook using the jest.mock() function. Here's a step-by-step guide:

Let's assume you have a custom hook called useCustomHook that returns a function named doSomething:

jsx
// useCustomHook.js import { useState } from 'react'; function useCustomHook() { const [count, setCount] = useState(0); const doSomething = () => { // Some logic... }; return { count, doSomething }; } export default useCustomHook;

To mock the doSomething function during testing:

  1. Create a Mock Function: In your test file, create a mock function using jest.fn():
jsx
// useCustomHook.test.js import { renderHook } from '@testing-library/react-hooks'; import useCustomHook from './useCustomHook'; // Create a mock for the doSomething function const mockDoSomething = jest.fn(); // Mock the useCustomHook jest.mock('./useCustomHook', () => { return jest.fn(() => ({ count: 0, doSomething: mockDoSomething, })); }); // Test cases...
  1. Write Your Test Cases: Now you can write your test cases using the mocked version of the useCustomHook. For example, if you want to test the behavior of the component that uses useCustomHook, you can render the component using renderHook from @testing-library/react-hooks.
jsx
// useCustomHook.test.js import { renderHook } from '@testing-library/react-hooks'; import useCustomHook from './useCustomHook'; // Create a mock for the doSomething function const mockDoSomething = jest.fn(); // Mock the useCustomHook jest.mock('./useCustomHook', () => { return jest.fn(() => ({ count: 0, doSomething: mockDoSomething, })); }); test('your test case', () => { // Write your test case using renderHook });

In this example, we create a mock function mockDoSomething and use jest.mock() to replace the original useCustomHook implementation with a mock version. The mocked version returns a fixed value for count (in this case, 0) and uses the mockDoSomething function as the returned doSomething function.

By doing this, whenever your component calls doSomething from the useCustomHook, it will actually be using the mockDoSomething mock function instead. You can then use mockDoSomething to assert if certain functions were called, how many times they were called, or to provide specific return values during your test cases.

Have questions or queries?
Get in Touch