Skip to content

Commit

Permalink
Merge branch 'develop-postgres' into chat-vitest
Browse files Browse the repository at this point in the history
  • Loading branch information
NishantSinghhhhh authored Dec 13, 2024
2 parents bebcd08 + f4aafd7 commit 19722f0
Show file tree
Hide file tree
Showing 12 changed files with 338 additions and 254 deletions.
1 change: 1 addition & 0 deletions .github/workflows/check-tsdoc.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ async function findTsxFiles(dir) {
} else if (
filePath.endsWith('.tsx') &&
!filePath.endsWith('.test.tsx') &&
!filePath.endsWith('.spec.tsx') &&
!filesToSkip.includes(path.relative(dir, filePath))
) {
results.push(filePath);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,36 +1,48 @@
import type { ReactElement } from 'react';
import React from 'react';
import { MockedProvider } from '@apollo/react-testing';
import type { RenderResult } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import 'jest-location-mock';
import { I18nextProvider } from 'react-i18next';
import { Provider } from 'react-redux';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes } from 'react-router-dom';

import { Provider } from 'react-redux';
import { I18nextProvider } from 'react-i18next';
import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { MockedProvider } from '@apollo/react-testing';
import { store } from 'state/store';
import { StaticMockLink } from 'utils/StaticMockLink';
import i18nForTest from 'utils/i18nForTest';
import { StaticMockLink } from 'utils/StaticMockLink';
import OrgSettings from './OrgSettings';
import userEvent from '@testing-library/user-event';
import type { ApolloLink } from '@apollo/client';
import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { MOCKS } from './OrgSettings.mocks';

const link1 = new StaticMockLink(MOCKS);

const renderOrganisationSettings = (link: ApolloLink): RenderResult => {
const mockRouterParams = (orgId: string | undefined): void => {
vi.doMock('react-router-dom', async () => {
const actual = await vi.importActual('react-router-dom');
return {
...actual,
useParams: () => ({ orgId }),
};
});
};
const renderOrganisationSettings = (
link = link1,
orgId = 'orgId',
): ReturnType<typeof render> => {
mockRouterParams(orgId);
return render(
<MockedProvider addTypename={false} link={link}>
<MemoryRouter initialEntries={['/orgsetting/orgId']}>
<MemoryRouter initialEntries={[`/orgsetting/${orgId}`]}>
<Provider store={store}>
<LocalizationProvider dateAdapter={AdapterDayjs}>
<I18nextProvider i18n={i18nForTest}>
<Routes>
<Route path="/orgsetting/:orgId" element={<OrgSettings />} />
<Route
path="/"
element={<div data-testid="paramsError"></div>}
element={
<div data-testid="paramsError">Redirected to Home</div>
}
/>
</Routes>
</I18nextProvider>
Expand All @@ -42,42 +54,54 @@ const renderOrganisationSettings = (link: ApolloLink): RenderResult => {
};

describe('Organisation Settings Page', () => {
beforeAll(() => {
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useParams: () => ({ orgId: 'orgId' }),
}));
afterEach(() => {
vi.unmock('react-router-dom');
});

afterAll(() => {
jest.clearAllMocks();
});
const SetupRedirectTest = async (): Promise<ReactElement> => {
const useParamsMock = vi.fn(() => ({ orgId: undefined }));
vi.doMock('react-router-dom', async () => {
const actual = await vi.importActual('react-router-dom');
return {
...actual,
useParams: useParamsMock,
};
});
const orgSettingsModule = await import('./OrgSettings');
return <orgSettingsModule.default />;
};

it('should redirect to fallback URL if URL params are undefined', async () => {
const OrgSettings = await SetupRedirectTest();
render(
<MockedProvider addTypename={false} link={link1}>
<MockedProvider addTypename={false}>
<MemoryRouter initialEntries={['/orgsetting/']}>
<Provider store={store}>
<I18nextProvider i18n={i18nForTest}>
<Routes>
<Route path="/orgsetting/" element={<OrgSettings />} />
<Route path="/orgsetting/" element={OrgSettings} />
<Route
path="/"
element={<div data-testid="paramsError"></div>}
element={
<div data-testid="paramsError">Redirected to Home</div>
}
/>
</Routes>
</I18nextProvider>
</Provider>
</MemoryRouter>
</MockedProvider>,
);

await waitFor(() => {
expect(screen.getByTestId('paramsError')).toBeInTheDocument();
const paramsErrorElement = screen.getByTestId('paramsError');
expect(paramsErrorElement).toBeInTheDocument();
expect(paramsErrorElement.textContent).toBe('Redirected to Home');
});
});

test('should render the organisation settings page', async () => {
renderOrganisationSettings(link1);
it('should render the organisation settings page', async () => {
renderOrganisationSettings();

await waitFor(() => {
expect(screen.getByTestId('generalSettings')).toBeInTheDocument();
Expand All @@ -88,10 +112,11 @@ describe('Organisation Settings Page', () => {
screen.getByTestId('agendaItemCategoriesSettings'),
).toBeInTheDocument();
});
userEvent.click(screen.getByTestId('generalSettings'));

userEvent.click(screen.getByTestId('generalSettings'));
await waitFor(() => {
expect(screen.getByTestId('generalTab')).toBeInTheDocument();
expect(screen.getByTestId('generalTab')).toBeVisible();
});

userEvent.click(screen.getByTestId('actionItemCategoriesSettings'));
Expand All @@ -104,4 +129,19 @@ describe('Organisation Settings Page', () => {
expect(screen.getByTestId('agendaItemCategoriesTab')).toBeInTheDocument();
});
});

it('should render dropdown for settings tabs', async () => {
renderOrganisationSettings();

await waitFor(() => {
expect(screen.getByTestId('settingsDropdownToggle')).toBeInTheDocument();
});

userEvent.click(screen.getByTestId('settingsDropdownToggle'));

const dropdownItems = screen.getAllByRole('button', {
name: /general|actionItemCategories|agendaItemCategories/i,
});
expect(dropdownItems).toHaveLength(3);
});
});
35 changes: 0 additions & 35 deletions src/screens/OrganizationDashboard/OrganizationDashboard.module.css

This file was deleted.

17 changes: 10 additions & 7 deletions src/screens/OrganizationDashboard/OrganizationDashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import type {
InterfaceQueryOrganizationsListObject,
InterfaceVolunteerRank,
} from 'utils/interfaces';
import styles from './OrganizationDashboard.module.css';
import styles from 'style/app.module.css';
import { VOLUNTEER_RANKING } from 'GraphQl/Queries/EventVolunteerQueries';

/**
Expand All @@ -41,7 +41,7 @@ import { VOLUNTEER_RANKING } from 'GraphQl/Queries/EventVolunteerQueries';
*
* @returns The rendered component.
*/
function organizationDashboard(): JSX.Element {
function OrganizationDashboard(): JSX.Element {
const { t } = useTranslation('translation', { keyPrefix: 'dashboard' });
const { t: tCommon } = useTranslation('common');
const { t: tErrors } = useTranslation('errors');
Expand Down Expand Up @@ -299,7 +299,7 @@ function organizationDashboard(): JSX.Element {
{t('viewAll')}
</Button>
</div>
<Card.Body className={styles.cardBody}>
<Card.Body className={styles.containerBody}>
{loadingEvent ? (
[...Array(4)].map((_, index) => {
return <CardItemLoading key={`eventLoading_${index}`} />;
Expand Down Expand Up @@ -341,7 +341,7 @@ function organizationDashboard(): JSX.Element {
{t('viewAll')}
</Button>
</div>
<Card.Body className={styles.cardBody}>
<Card.Body className={styles.containerBody}>
{loadingPost ? (
[...Array(4)].map((_, index) => {
return <CardItemLoading key={`postLoading_${index}`} />;
Expand Down Expand Up @@ -392,7 +392,7 @@ function organizationDashboard(): JSX.Element {
</Button>
</div>
<Card.Body
className={styles.cardBody}
className={styles.containerBody}
style={{ height: '150px' }}
>
{loadingOrgData ? (
Expand Down Expand Up @@ -435,7 +435,10 @@ function organizationDashboard(): JSX.Element {
{t('viewAll')}
</Button>
</div>
<Card.Body className={styles.cardBody} style={{ padding: '0px' }}>
<Card.Body
className={styles.containerBody}
style={{ padding: '0px' }}
>
{rankingsLoading ? (
[...Array(3)].map((_, index) => {
return <CardItemLoading key={`rankingLoading_${index}`} />;
Expand Down Expand Up @@ -483,4 +486,4 @@ function organizationDashboard(): JSX.Element {
);
}

export default organizationDashboard;
export default OrganizationDashboard;
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import React, { act } from 'react';
import { MockedProvider } from '@apollo/react-testing';
import { render, screen } from '@testing-library/react';
import 'jest-localstorage-mock';
import 'jest-location-mock';
import { I18nextProvider } from 'react-i18next';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
Expand All @@ -22,6 +20,34 @@ import {
MOCKS4,
} from './RequestsMocks';
import useLocalStorage from 'utils/useLocalstorage';
import { vi } from 'vitest';

/**
* Set up `localStorage` stubs for testing.
*/

vi.stubGlobal('localStorage', {
getItem: vi.fn(),
setItem: vi.fn(),
clear: vi.fn(),
removeItem: vi.fn(),
});

/**
* Mock `window.location` for testing redirection behavior.
*/

Object.defineProperty(window, 'location', {
value: {
href: 'http://localhost/',
assign: vi.fn(),
reload: vi.fn(),
pathname: '/',
search: '',
hash: '',
origin: 'http://localhost',
},
});

const { setItem, removeItem } = useLocalStorage();

Expand All @@ -33,6 +59,14 @@ const link5 = new StaticMockLink(MOCKS_WITH_ERROR, true);
const link6 = new StaticMockLink(MOCKS3, true);
const link7 = new StaticMockLink(MOCKS4, true);

/**
* Utility function to wait for a specified amount of time.
* Wraps `setTimeout` in an `act` block for testing purposes.
*
* @param ms - The duration to wait in milliseconds. Default is 100ms.
* @returns A promise that resolves after the specified time.
*/

async function wait(ms = 100): Promise<void> {
await act(() => {
return new Promise((resolve) => {
Expand All @@ -53,7 +87,6 @@ afterEach(() => {

describe('Testing Requests screen', () => {
test('Component should be rendered properly', async () => {
const loadMoreRequests = jest.fn();
render(
<MockedProvider addTypename={false} link={link7}>
<BrowserRouter>
Expand Down
Loading

0 comments on commit 19722f0

Please sign in to comment.