Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor src/components/OrgSettings/ActionItemCategories/* from Jest to Vitest #2916

Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,23 @@ import { MOCKS, MOCKS_ERROR } from './OrgActionItemCategoryMocks';
import type { InterfaceActionItemCategoryModal } from './CategoryModal';
import CategoryModal from './CategoryModal';
import { toast } from 'react-toastify';

jest.mock('react-toastify', () => ({
import { vi } from 'vitest';
/**
* This file contains unit tests for the `CategoryModal` component.
*
* The tests cover:
* - Proper rendering of the component in various scenarios, including `create` and `edit` modes, mock data, and error states.
* - Handling user interactions with form fields, such as updating the category name and toggling the `isDisabled` switch.
* - Ensuring form submissions trigger appropriate callbacks (e.g., `refetchCategories` and `hide`) and display correct toast notifications.
* - Simulating GraphQL query and mutation operations with mocked data to validate behavior in success and error cases.
* - Testing edge cases, such as submitting without changes, invalid inputs, and handling API errors gracefully.
* - Verifying proper integration of internationalization, Redux state, routing, and toast notifications for success and error feedback.
*/

vi.mock('react-toastify', () => ({
toast: {
success: jest.fn(),
error: jest.fn(),
success: vi.fn(),
error: vi.fn(),
},
}));

Expand All @@ -37,8 +49,8 @@ const translations = {
const categoryProps: InterfaceActionItemCategoryModal[] = [
{
isOpen: true,
hide: jest.fn(),
refetchCategories: jest.fn(),
hide: vi.fn(),
refetchCategories: vi.fn(),
orgId: 'orgId',
mode: 'create',
category: {
Expand All @@ -51,8 +63,8 @@ const categoryProps: InterfaceActionItemCategoryModal[] = [
},
{
isOpen: true,
hide: jest.fn(),
refetchCategories: jest.fn(),
hide: vi.fn(),
refetchCategories: vi.fn(),
orgId: 'orgId',
mode: 'edit',
category: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,36 @@ import i18n from 'utils/i18nForTest';
import type { ApolloLink } from '@apollo/client';
import { MOCKS, MOCKS_EMPTY, MOCKS_ERROR } from './OrgActionItemCategoryMocks';
import OrgActionItemCategories from './OrgActionItemCategories';

jest.mock('react-toastify', () => ({
import { vi } from 'vitest';

/**
* This file contains unit tests for the `OrgActionItemCategories` component.
*
* The tests cover:
* - Proper rendering of the component under different conditions, including scenarios with populated categories, empty categories, and API errors.
* - User interactions such as searching, filtering, sorting categories, and opening/closing modals for creating or editing categories.
* - Verification of GraphQL query and mutation behaviors using mock data, ensuring correct functionality in both success and error cases.
* - Handling edge cases like no input, invalid input, and form resets.
* - Integration tests for Redux state, routing, internationalization, and toast notifications.
* - Ensuring sorting functionality reflects the `createdAt` property both in ascending and descending order.
* - Testing the modal interactions for creating and editing categories, ensuring proper lifecycle (open/close) and state updates.
* - Checking the rendering of error messages and placeholders when no data is available or an error occurs.
* - Validation of search functionality for categories by name, including clearing the search input and using keyboard shortcuts like `Enter`.
*/

vi.mock('react-toastify', () => ({
toast: {
success: jest.fn(),
error: jest.fn(),
success: vi.fn(),
error: vi.fn(),
},
}));

jest.mock('@mui/x-date-pickers/DateTimePicker', () => {
vi.mock('@mui/x-date-pickers/DateTimePicker', async () => {
const dateTimePickerModule = await vi.importActual(
'@mui/x-date-pickers/DesktopDateTimePicker',
);
return {
DateTimePicker: jest.requireActual(
'@mui/x-date-pickers/DesktopDateTimePicker',
).DesktopDateTimePicker,
DateTimePicker: dateTimePickerModule.DesktopDateTimePicker,
};
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,30 +1,40 @@
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MockedProvider } from '@apollo/react-testing';
import { I18nextProvider } from 'react-i18next';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import { store } from 'state/store';
import i18nForTest from 'utils/i18nForTest';

import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';

import AgendaCategoryCreateModal from './AgendaCategoryCreateModal';
import { vi } from 'vitest';
/**
* This file contains unit tests for the `AgendaCategoryCreateModal` component.
*
* The tests cover:
* - Rendering of the modal, ensuring all elements such as form fields, buttons, and labels are displayed correctly.
* - Behavior of form inputs, including updating the `formState` when the `name` and `description` fields are changed.
* - Proper invocation of the `createAgendaCategoryHandler` when the form is submitted.
* - Integration of Redux state, routing, localization (i18n), and date-picker utilities to ensure compatibility and proper rendering.
* - Validations for form controls to check user interactions, including typing and submitting the form.
* - Mock function verifications for `setFormState`, `hideCreateModal`, and other handlers to ensure state changes and actions are triggered appropriately.
* - Handling edge cases, such as empty fields or invalid data, ensuring graceful degradation of functionality.
*/

const mockFormState = {
name: 'Test Name',
description: 'Test Description',
createdBy: 'Test User',
};
const mockHideCreateModal = jest.fn();
const mockSetFormState = jest.fn();
const mockCreateAgendaCategoryHandler = jest.fn();
const mockHideCreateModal = vi.fn();
const mockSetFormState = vi.fn();
const mockCreateAgendaCategoryHandler = vi.fn();
const mockT = (key: string): string => key;

describe('AgendaCategoryCreateModal', () => {
test('renders modal correctly', () => {
it('renders modal correctly', () => {
render(
<MockedProvider addTypename={false}>
<Provider store={store}>
Expand Down Expand Up @@ -54,7 +64,7 @@ describe('AgendaCategoryCreateModal', () => {
screen.getByTestId('createAgendaCategoryModalCloseBtn'),
).toBeInTheDocument();
});
test('tests the condition for formState.name and formState.description', () => {
it('tests the condition for formState.name and formState.description', () => {
const mockFormState = {
name: 'Test Name',
description: 'Test Description',
Expand Down Expand Up @@ -97,7 +107,7 @@ describe('AgendaCategoryCreateModal', () => {
description: 'New description',
});
});
test('calls createAgendaCategoryHandler when form is submitted', () => {
it('calls createAgendaCategoryHandler when form is submitted', () => {
render(
<MockedProvider addTypename={false}>
<Provider store={store}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,36 @@ import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import { store } from 'state/store';
import i18nForTest from 'utils/i18nForTest';

import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';

import AgendaCategoryUpdateModal from './AgendaCategoryUpdateModal';
import { vi } from 'vitest';

/**
* Unit tests for `AgendaCategoryUpdateModal`:
*
* - **Rendering**: Verifies key elements (e.g., text, buttons) render correctly.
* - **Close Button**: Ensures `hideUpdateModal` is called on close.
* - **Form Inputs**: Confirms `setFormState` updates with new `name` and `description`.
* - **Submission**: Checks `updateAgendaCategoryHandler` triggers on submit.
* - **Integration**: Validates compatibility with Redux, routing, i18n, and MUI date-picker.
* - **Mocks**: Ensures handlers (`setFormState`, `hideUpdateModal`, `updateAgendaCategoryHandler`) are called with correct arguments.
*
* This suite ensures component reliability and behavior consistency.
*/

const mockFormState = {
name: 'Test Name',
description: 'Test Description',
createdBy: 'Test User',
};
const mockHideUpdateModal = jest.fn();
const mockSetFormState = jest.fn();
const mockUpdateAgendaCategoryHandler = jest.fn();
const mockHideUpdateModal = vi.fn();
const mockSetFormState = vi.fn();
const mockUpdateAgendaCategoryHandler = vi.fn();
const mockT = (key: string): string => key;

describe('AgendaCategoryUpdateModal', () => {
test('renders modal correctly', () => {
it('renders modal correctly', () => {
render(
<MockedProvider addTypename={false}>
<Provider store={store}>
Expand Down Expand Up @@ -53,7 +65,7 @@ describe('AgendaCategoryUpdateModal', () => {
).toBeInTheDocument();
});

test('calls hideUpdateModal when close button is clicked', () => {
it('calls hideUpdateModal when close button is clicked', () => {
render(
<MockedProvider addTypename={false}>
<Provider store={store}>
Expand All @@ -79,7 +91,7 @@ describe('AgendaCategoryUpdateModal', () => {
expect(mockHideUpdateModal).toHaveBeenCalledTimes(1);
});

test('tests the condition for formState.name and formState.description', () => {
it('tests the condition for formState.name and formState.description', () => {
const mockFormState = {
name: 'Test Name',
description: 'Test Description',
Expand Down Expand Up @@ -123,7 +135,7 @@ describe('AgendaCategoryUpdateModal', () => {
});
});

test('calls updateAgendaCategoryHandler when form is submitted', () => {
it('calls updateAgendaCategoryHandler when form is submitted', () => {
render(
<MockedProvider addTypename={false}>
<Provider store={store}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
waitForElementToBeRemoved,
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import 'jest-localstorage-mock';
import { MockedProvider } from '@apollo/client/testing';
import 'jest-location-mock';
import { I18nextProvider } from 'react-i18next';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
Expand All @@ -22,23 +20,38 @@
import { StaticMockLink } from 'utils/StaticMockLink';

import OrganizationAgendaCategory from './OrganizationAgendaCategory';
import {
MOCKS_ERROR_AGENDA_ITEM_CATEGORY_LIST_QUERY,
MOCKS_ERROR_MUTATION,
} from './OrganizationAgendaCategoryErrorMocks';
import { MOCKS_ERROR_AGENDA_ITEM_CATEGORY_LIST_QUERY } from './OrganizationAgendaCategoryErrorMocks';
import { MOCKS } from './OrganizationAgendaCategoryMocks';

jest.mock('react-toastify', () => ({
import { vi } from 'vitest';

/**
* Unit Tests for `OrganizationAgendaCategory` Component
*
* - **Load Component**: Verifies successful rendering of key elements like `createAgendaCategory`.
* - **Error Handling**: Confirms error view appears when agenda category list query fails.
* - **Modal Functionality**:
* - Opens and closes the create agenda category modal.
* - Ensures `createAgendaCategoryModalCloseBtn` disappears on close.
* - **Create Agenda Category**:
* - Simulates filling the form and submission.
* - Verifies success toast on successful creation (`agendaCategoryCreated`).
* - **Integration**: Validates compatibility with Redux, Apollo, i18n, and MUI date-picker.
*/

vi.mock('react-toastify', () => ({
toast: {
success: jest.fn(),
error: jest.fn(),
success: vi.fn(),
error: vi.fn(),
},
}));

jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useParams: () => ({ orgId: '123' }),
}));
vi.mock('react-router-dom', async () => {
const actual = await vi.importActual('react-router-dom');
return {
...actual,
useParams: () => ({ orgId: '123' }),
};
});

async function wait(ms = 100): Promise<void> {
await act(() => {
Expand All @@ -53,8 +66,6 @@
MOCKS_ERROR_AGENDA_ITEM_CATEGORY_LIST_QUERY,
true,
);
const link3 = new StaticMockLink(MOCKS_ERROR_MUTATION, true);

const translations = {
...JSON.parse(
JSON.stringify(
Expand All @@ -70,7 +81,7 @@
description: 'Test Description',
createdBy: 'Test User',
};
test('Component loads correctly', async () => {
it('Component loads correctly', async () => {
const { getByText } = render(
<MockedProvider addTypename={false} link={link}>
<Provider store={store}>
Expand All @@ -90,7 +101,7 @@
});
});

test('render error component on unsuccessful agenda category list query', async () => {
it('render error component on unsuccessful agenda category list query', async () => {
const { queryByText } = render(
<MockedProvider addTypename={false} link={link2}>
<Provider store={store}>
Expand All @@ -112,7 +123,7 @@
});
});

test('opens and closes the create agenda category modal', async () => {
it('opens and closes the create agenda category modal', async () => {
render(
<MockedProvider addTypename={false} link={link}>
<Provider store={store}>
Expand Down Expand Up @@ -145,7 +156,7 @@
screen.queryByTestId('createAgendaCategoryModalCloseBtn'),
);
});
test('creates new agenda cagtegory', async () => {
it('creates new agenda cagtegory', async () => {
render(
<MockedProvider addTypename={false} link={link}>
<Provider store={store}>
Expand Down Expand Up @@ -191,7 +202,7 @@
});
});

// test('toasts error on unsuccessful creation', async () => {

Check warning on line 205 in src/components/OrgSettings/AgendaItemCategories/OrganizationAgendaCategory.spec.tsx

View workflow job for this annotation

GitHub Actions / Performs linting, formatting, type-checking, checking for different source and target branch

Some tests seem to be commented
// render(
// <MockedProvider addTypename={false} link={link3}>
// <Provider store={store}>
Expand Down
Loading
Loading