javascriptreactjsreact-testing-libraryvitestreact-custom-hooks

How can I test a function that is inside a custom hook to work as it is expected?


I have a custom hook that I want to test (I'm using vitest for testing).. Here is the custom hook.

export const useRerunCustomQuery = (attributes) => {
  const {id, staticCustomId, featureSelection} = attributes;


  const updateCustomMutation = useMutation({
    mutationFn : (params) => updateStaticCustom(params),
  });

  const saveNewCustomSize = async(staticCustomId, size) => {
    if (!staticCustomId) {
      return null;
    }

    const payload = {
      id   : staticCustomId,
      data : {
        type       : 'StaticCustom',
        id         : staticCustomId,
        attributes : {
          size         : size,
          dateExecuted : getCurrentDate(),
          updatedAt    : getCurrentDate()
        }
      },
    };

    return await updateCustomMutation.mutateAsync(payload);
  };

  const rerunCustomQuery = async() => {
    if (staticCustomId) {
      toggleLoadingState(id, true);

      const patient_count = rerunResponse.data.data.data[MODELS.PATIENT_COUNT];
      await saveNewCustomSize(staticCustomId, patient_count);

      toggleLoadingState(id, false);
    }
  };

  return {
    rerunCustomQuery,
  };
};

I want to test the saveNewCustomSize but I can't get a hold of it. Here is my test approach so far:

import React from 'react';
import {renderHook} from '@testing-library/react'; 
import {it, vi} from 'vitest';
import {ProvidersWrapper} from '@/src/utils/TestUtils';
import {useRerunCustomQuery} from './useRerunCustomQuery';

vi.mock('@/core/src/services', () => ({
  updateStaticCustom: vi.fn()
}))

it('should call saveNewCustomSize with correct parameters', async () => {

    let attributes = vi.fn();
    const staticCustomId = '111';
    const size = 5;
    const getCurrentDate = vi.fn().mockReturnValue('2024-02-14');

    const {result} = renderHook(() => useRerunCustomQuery(attributes), {
        wrapper: ProvidersWrapper
    })

    result.current.rerunCustomQuery()
   
    expect(updateStaticCustom).toHaveBeenCalledWith({
      id: staticCustomId,
      data: {
        type: 'StaticCustom',
        id: staticCustomId,
        attributes: {
          size: size,
          dateExecuted: "2024-02-14",
          updatedAt: "2024-02-14",
        },
      },
    });
  });


I tried to call the rerunCustomQuery that should invoke saveNewCustomSize and expected the updateStaticCustom toHaveBeenCalledWith the payload object. But I'm getting AssertionError: expected "spy" to be called with arguments: [ { id: '111', data: { …(3) } } ]


Solution

  • Don't you need to pass some parameters to useRerunCustomQuery? You are using it without it.

       const {result} = renderHook(() => useRerunCustomQuery(), {
            wrapper: ProvidersWrapper
        })