Ошибка TypeError: children is not a function указывает на то, что параметры, передаваемые в children, не совпадают с тем, что ожидается компонентом. Чтобы исправить это, нам нужно убедиться, что мок компонента ConditionConfigurator корректно передает children, которые могут быть функцией, когда она вызывается.
Попробуем еще раз исправить этот момент, удостоверившись, что моки правильно реализованы и возвращают то, что ожидается от дочерних компонентов. Мы сделаем несколько изменений для упрощения:
- Убедимся, что моки для компонентов правильно передают
children.
- Проверим, что все функции, которые передаются в компоненты, также правильно мокаются.
Вот исправленный код с учётом вышеизложенного:
import React from 'react';
import { render, screen } from '@testing-library/react';
import { AtypicalConditionModal } from './AtypicalConditionModal';
import { ConditionConfigurator } from '$conditions-constructor-v2-configuration';
import { EditConditionsForm } from '$conditions-constructor-v2/widgets/editConditionsForm';
import { EditConditionModal, EditConditionModalError, EditConditionModalSkeleton } from '$conditions-constructor-v2/widgets/editConditionsModal';
import { AtypicalConditionNameInput } from './AtypicalConditionNameInput';
// Мокаем необходимые компоненты
jest.mock('$conditions-constructor-v2-configuration', () => ({
ConditionConfigurator: ({ children }) => (
<div>{children({})}</div>
),
}));
jest.mock('$conditions-constructor-v2/widgets/editConditionsForm', () => ({
EditConditionsForm: ({ children }) => (
children({
editConditionTable: <div>Table</div>,
conditionErrorsInfoPanel: <div>Error Panel</div>,
initStatus: 'fulfilled',
retryInitConditionForm: jest.fn(),
saveCondition: jest.fn(),
})
),
}));
jest.mock('$conditions-constructor-v2/widgets/editConditionsModal', () => ({
EditConditionModal: ({ children, isOpen }) => (isOpen ? <div>{children}</div> : null),
EditConditionModalError: ({ onRepeat }) => <div onClick={onRepeat}>Error</div>,
EditConditionModalSkeleton: () => <div>Loading...</div>,
}));
jest.mock('./AtypicalConditionNameInput', () => () => <input data-testid="condition-name-input" />);
describe('AtypicalConditionModal', () => {
const defaultProps = {
onClose: jest.fn(),
docId: 1,
documentType: 'exampleType',
conditionCode: 'exampleCode',
conditionId: 'exampleId',
disabled: false,
};
it('renders condition name input, error panel and edit condition table when initStatus is fulfilled', () => {
render(<AtypicalConditionModal active={true} {...defaultProps} />);
expect(screen.getByTestId('condition-name-input')).toBeInTheDocument();
expect(screen.getByText('Error Panel')).toBeInTheDocument();
expect(screen.getByText('Table')).toBeInTheDocument();
});
it('renders error modal when initStatus is rejected', () => {
jest.mock('$conditions-constructor-v2/widgets/editConditionsForm', () => ({
EditConditionsForm: ({ children }) => (
children({
editConditionTable: <div>Table</div>,
conditionErrorsInfoPanel: <div>Error Panel</div>,
initStatus: 'rejected',
retryInitConditionForm: jest.fn(),
saveCondition: jest.fn(),
})
),
}));
render(<AtypicalConditionModal active={true} {...defaultProps} />);
expect(screen.getByText('Error')).toBeInTheDocument();
});
it('renders loading skeleton when initStatus is pending', () => {
jest.mock('$conditions-constructor-v2/widgets/editConditionsForm', () => ({
EditConditionsForm: ({ children }) => (
children({
editConditionTable: <div>Table</div>,
conditionErrorsInfoPanel: <div>Error Panel</div>,
initStatus: 'pending',
retryInitConditionForm: jest.fn(),
saveCondition: jest.fn(),
})
),
}));
render(<AtypicalConditionModal active={true} {...defaultProps} />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
});
});
Изменения
-
Исправленный мок для ConditionConfigurator: Теперь он создаёт элемент div, который оборачивает вызов children({}), чтобы правильно обрабатывать их как React элемент.
-
Переопределение мока EditConditionsForm: Теперь это выполняется локально в каждом тесте с нужными значениями, чтобы отобразить разные состояния.
Эти изменения должны исправить ошибку и сделать тесты работоспособными. Если ошибки будут продолжаться, вам может понадобиться просмотреть другие моки или логику, чтобы убедиться, что они соответствуют ожидаемому поведению вашего компонента.