我有一个想要测试的自定义钩子(我正在使用 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) } } ]
不需要传递一些参数给
useRerunCustomQuery
吗?你在没有它的情况下使用它。
const {result} = renderHook(() => useRerunCustomQuery(), {
wrapper: ProvidersWrapper
})