如何测试自定义挂钩内的函数是否按预期工作?

问题描述 投票:0回答:1

我有一个想要测试的自定义钩子(我正在使用 vitest 进行测试).. 这是自定义挂钩。

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,
  };
};

我想测试

saveNewCustomSize
,但我无法掌握它。这是到目前为止我的测试方法:

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 () => {

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

    const {result} = renderHook(() => useRerunCustomQuery(), {
        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",
        },
      },
    });
  });


我尝试调用应该调用

rerunCustomQuery
saveNewCustomSize
并期望
updateStaticCustom
toHaveBeenCalledWith
payload
对象。但我越来越
AssertionError: expected "spy" to be called with arguments: [ { id: '111', data: { …(3) } } ]

reactjs react-hooks react-testing-library vitest
1个回答
0
投票

不需要传递一些参数给

useRerunCustomQuery
吗?你在没有它的情况下使用它。

   const {result} = renderHook(() => useRerunCustomQuery(), {
        wrapper: ProvidersWrapper
    }) 
© www.soinside.com 2019 - 2024. All rights reserved.