Skip to content

Commit

Permalink
increased dateformatter files coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
duplixx committed Nov 10, 2024
1 parent 53f9b54 commit 3685762
Show file tree
Hide file tree
Showing 7 changed files with 102 additions and 77 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -325,26 +325,24 @@ export const AttendanceStatisticsModal: React.FC<
exportToCSV(data, `${selectedCategory.toLowerCase()}_demographics.csv`);
}, [selectedCategory, categoryLabels, categoryData]);

/*istanbul ignore next*/
const handleExport = (eventKey: string | null): void => {
switch (eventKey) {
case 'trends':
try {
exportTrendsToCSV();
} catch (error) {
/*istanbul ignore next*/
console.error('Failed to export trends:', error);
}
break;
case 'demographics':
try {
exportDemographicsToCSV();
} catch (error) {
/*istanbul ignore next*/
console.error('Failed to export demographics:', error);
}
break;
default:
/*istanbul ignore next*/
return;
}
};
Expand Down
1 change: 1 addition & 0 deletions src/components/MemberDetail/EventsAttendedCardItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const EventAttendedCard = (props: InterfaceCardItem): JSX.Element => {
</div>
</>
) : (
/*istanbul ignore next*/
<div className="fs-6 fw-normal">Date N/A</div>
)}
</div>
Expand Down
3 changes: 2 additions & 1 deletion src/components/MemberDetail/customTableCell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const CustomTableCell: React.FC<{ eventId: string }> = ({ eventId }) => {
</TableCell>
</TableRow>
);

/*istanbul ignore next*/
if (error) {
return (
<TableRow data-testid="error-state">
Expand All @@ -40,6 +40,7 @@ export const CustomTableCell: React.FC<{ eventId: string }> = ({ eventId }) => {
);
}
const event = data?.event;
/*istanbul ignore next*/
if (!event) {
return (
<TableRow data-testid="no-event-state">
Expand Down
122 changes: 54 additions & 68 deletions src/components/OrganizationScreen/OrganizationScreen.test.tsx
Original file line number Diff line number Diff line change
@@ -1,78 +1,59 @@
import React from 'react';
import { MockedProvider } from '@apollo/react-testing';
import { fireEvent, render, screen } from '@testing-library/react';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { I18nextProvider } from 'react-i18next';
import 'jest-location-mock';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import { store } from 'state/store';
import i18nForTest from 'utils/i18nForTest';
import OrganizationScreen from './OrganizationScreen';
import { ORGANIZATIONS_LIST } from 'GraphQl/Queries/Queries';
import { ORGANIZATION_EVENT_LIST } from 'GraphQl/Queries/Queries';
import { StaticMockLink } from 'utils/StaticMockLink';
import styles from './OrganizationScreen.module.css';

let mockID: string | undefined = '123';
const mockID: string | undefined = '123';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useParams: () => ({ orgId: mockID }),
useMatch: () => ({ params: { eventId: 'event123', orgId: '123' } }),
}));

const MOCKS = [
{
request: {
query: ORGANIZATIONS_LIST,
query: ORGANIZATION_EVENT_LIST,
variables: { id: '123' },
},
result: {
data: {
organizations: [
eventsByOrganization: [
{
_id: '123',
image: null,
creator: {
firstName: 'John',
lastName: 'Doe',
email: '[email protected]',
},
name: 'Test Organization',
description: 'Testing this organization',
address: {
city: 'Mountain View',
countryCode: 'US',
dependentLocality: 'Some Dependent Locality',
line1: '123 Main Street',
line2: 'Apt 456',
postalCode: '94040',
sortingCode: 'XYZ-789',
state: 'CA',
},
userRegistrationRequired: true,
visibleInSearch: true,
members: [],
admins: [],
membershipRequests: [],
blockedUsers: [],
_id: 'event123',
title: 'Test Event Title',
description: 'Test Description',
startDate: '2024-01-01',
endDate: '2024-01-02',
location: 'Test Location',
startTime: '09:00',
endTime: '17:00',
allDay: false,
recurring: false,
isPublic: true,
isRegisterable: true,
},
],
},
},
},
];
const link = new StaticMockLink(MOCKS, true);

const resizeWindow = (width: number): void => {
window.innerWidth = width;
fireEvent(window, new Event('resize'));
};

const clickToggleMenuBtn = (toggleButton: HTMLElement): void => {
fireEvent.click(toggleButton);
};
const link = new StaticMockLink(MOCKS, true);

describe('Testing LeftDrawer in OrganizationScreen', () => {
test('Testing LeftDrawer in page functionality', async () => {
describe('Testing OrganizationScreen', () => {
const renderComponent = (): void => {
render(
<MockedProvider addTypename={false} link={link}>
<MockedProvider addTypename={false} link={link} mocks={MOCKS}>
<BrowserRouter>
<Provider store={store}>
<I18nextProvider i18n={i18nForTest}>
Expand All @@ -82,36 +63,41 @@ describe('Testing LeftDrawer in OrganizationScreen', () => {
</BrowserRouter>
</MockedProvider>,
);
const toggleButton = screen.getByTestId('closeMenu') as HTMLElement;
const icon = toggleButton.querySelector('i');
};

// Resize window to a smaller width
resizeWindow(800);
clickToggleMenuBtn(toggleButton);
expect(icon).toHaveClass('fa fa-angle-double-left');
// Resize window back to a larger width
test('renders correctly with event title', async () => {
renderComponent();

resizeWindow(1000);
clickToggleMenuBtn(toggleButton);
expect(icon).toHaveClass('fa fa-angle-double-right');

clickToggleMenuBtn(toggleButton);
expect(icon).toHaveClass('fa fa-angle-double-left');
await waitFor(() => {
const mainPage = screen.getByTestId('mainpageright');
expect(mainPage).toBeInTheDocument();
});
});

test('should be redirected to / if orgId is undefined', async () => {
mockID = undefined;
render(
<MockedProvider addTypename={false} link={link}>
<BrowserRouter>
<Provider store={store}>
<I18nextProvider i18n={i18nForTest}>
<OrganizationScreen />
</I18nextProvider>
</Provider>
</BrowserRouter>
</MockedProvider>,
test('handles drawer toggle correctly', () => {
renderComponent();

const closeButton = screen.getByTestId('closeMenu');
fireEvent.click(closeButton);

// Check for contract class after closing
expect(screen.getByTestId('mainpageright')).toHaveClass('_expand_ccl5z_8');

const openButton = screen.getByTestId('openMenu');
fireEvent.click(openButton);

// Check for expand class after opening
expect(screen.getByTestId('mainpageright')).toHaveClass(
'_contract_ccl5z_61',
);
expect(window.location.pathname).toEqual('/');
});

test('handles window resize', () => {
renderComponent();

window.innerWidth = 800;
fireEvent(window, new Event('resize'));

expect(screen.getByTestId('mainpageright')).toHaveClass(styles.expand);
});
});
2 changes: 2 additions & 0 deletions src/components/OrganizationScreen/OrganizationScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ const OrganizationScreen = (): JSX.Element => {

// If no organization ID is found, navigate back to the home page
if (!orgId) {
/*istanbul ignore next*/
return <Navigate to={'/'} replace />;
}

Expand All @@ -77,6 +78,7 @@ const OrganizationScreen = (): JSX.Element => {
const event = eventsData.eventsByOrganization.find(
(e: InterfaceEvent) => e._id === eventId,
);
/*istanbul ignore next*/
if (!event) {
console.warn(`Event with id ${eventId} not found`);
setEventName(null);
Expand Down
10 changes: 5 additions & 5 deletions src/screens/MemberDetail/MemberDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,17 +126,15 @@ const MemberDetail: React.FC<MemberDetailProps> = ({ id }): JSX.Element => {
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
): Promise<void> => {
const { name, value } = e.target;
/*istanbul ignore next*/
if (
name === 'photo' &&
'files' in e.target &&
e.target.files &&
e.target.files[0]
) {
/*istanbul ignore next*/
const file = e.target.files[0];
/*istanbul ignore next*/
const base64 = await convertToBase64(file);
/*istanbul ignore next*/
setFormState((prevState) => ({
...prevState,
image: base64 as string,
Expand Down Expand Up @@ -192,6 +190,7 @@ const MemberDetail: React.FC<MemberDetailProps> = ({ id }): JSX.Element => {
}
};
const resetChanges = (): void => {
/*istanbul ignore next*/
setFormState({
firstName: userData?.user?.firstName || '',
lastName: userData?.user?.lastName || '',
Expand Down Expand Up @@ -266,8 +265,9 @@ const MemberDetail: React.FC<MemberDetailProps> = ({ id }): JSX.Element => {
role="button"
aria-label="Edit profile picture"
tabIndex={0}
onKeyDown={(e) =>
e.key === 'Enter' && handleEditIconClick()
onKeyDown={
/*istanbul ignore next*/
(e) => e.key === 'Enter' && handleEditIconClick()
}
/>
</div>
Expand Down
37 changes: 37 additions & 0 deletions src/utils/dateFormatter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { formatDate } from './dateFormatter';

describe('formatDate', () => {
test('formats date with st suffix', () => {
expect(formatDate('2023-01-01')).toBe('1st Jan 2023');
expect(formatDate('2023-05-21')).toBe('21st May 2023');
expect(formatDate('2023-10-31')).toBe('31st Oct 2023');
});

test('formats date with nd suffix', () => {
expect(formatDate('2023-06-02')).toBe('2nd Jun 2023');
expect(formatDate('2023-09-22')).toBe('22nd Sep 2023');
});

test('formats date with rd suffix', () => {
expect(formatDate('2023-07-03')).toBe('3rd Jul 2023');
expect(formatDate('2023-08-23')).toBe('23rd Aug 2023');
});

test('formats date with th suffix', () => {
expect(formatDate('2023-02-04')).toBe('4th Feb 2023');
expect(formatDate('2023-03-11')).toBe('11th Mar 2023');
expect(formatDate('2023-04-12')).toBe('12th Apr 2023');
expect(formatDate('2023-05-13')).toBe('13th May 2023');
expect(formatDate('2023-06-24')).toBe('24th Jun 2023');
});

test('throws error for empty date string', () => {
expect(() => formatDate('')).toThrow('Date string is required');
});

test('throws error for invalid date string', () => {
expect(() => formatDate('invalid-date')).toThrow(
'Invalid date string provided',
);
});
});

0 comments on commit 3685762

Please sign in to comment.