Я использую хуки для визуализации компонентов пользовательского интерфейса и пытаюсь их протестировать.
import React, { useState, useCallback } from 'react';
import { useModal } from './useModal';
import { ConfirmationModal } from './common';
export const useConfirm = () => {
// Manage if confirm module is open or close
// Provide callback to set confirm state
const { isShowing, toggle } = useModal();
// Track confirmation module values
const [confirmOptions, setConfirmOptions] = useState({});
// Callback to set confirmation model properties
const setConfirmation = useCallback(
async (title, body, onConfirm, onCancel) => {
await setConfirmOptions({
title,
body,
onConfirm,
onCancel
});
toggle();
},
[toggle]
);
const ConfirmModal = (
<ConfirmationModal
open={isShowing}
toggle={toggle}
title={confirmOptions.title}
content={confirmOptions.body}
onConfirm={confirmOptions.onConfirm}
onCancel={confirmOptions.onCancel}
/>
);
return {
setConfirmation,
ConfirmModal
};
};
Тест:
import { renderHook, act } from '@testing-library/react-hooks';
import { useConfirm } from './useConfirm';
describe('useConfirm hook', () => {
it('toggles confirm ui', () => {
const { result } = renderHook(() => useConfirm());
const onConfirm = jest.fn();
const onCancel = jest.fn();
// test confirm is called
act(() => {
result.current.setConfirmation(
'Title',
'Content Content',
onConfirm,
onCancel
);
console.log(result.current.ConfirmModal);
});
// test cancel is called
});
});
Я получаю:
Warning: An update to %s inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
Но это обертка.