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

PADV-1475 test: Creating test for shared componets and helper functions. #19

Merged
merged 2 commits into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions __mocks__/fileMock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = 'test-file-stub';
6 changes: 6 additions & 0 deletions babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
presets: [
['@babel/preset-env', { targets: { node: 'current' } }],
'@babel/preset-react',
],
};
14 changes: 14 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module.exports = {
moduleNameMapper: {
'^views/(.*)$': '<rootDir>/src/views/$1',
'^shared/(.*)$': '<rootDir>/src/shared/$1',
'^constants/(.*)$': '<rootDir>/src/constants/$1',
'\\.(css|less|scss|sass)$': 'identity-obj-proxy',
'\\.(svg|png|jpg|jpeg|gif)$': '<rootDir>/__mocks__/fileMock.js',
},
transform: {
'^.+\\.[t|j]sx?$': 'babel-jest',
},
transformIgnorePatterns: ['node_modules/(?!@edx/frontend-platform|@edx/paragon|react-paragon-topaz)'],
testEnvironment: 'jest-environment-jsdom',
};
5,273 changes: 3,735 additions & 1,538 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,16 @@
"regenerator-runtime": "0.13.9"
},
"devDependencies": {
"@babel/preset-env": "7.25.4",
"@babel/preset-react": "7.24.7",
"@edx/browserslist-config": "1.1.1",
"@edx/frontend-build": "9.2.2",
"@testing-library/jest-dom": "6.5.0",
"@testing-library/react": "12.1.5",
"es-check": "5.2.4",
"glob": "7.2.3",
"husky": "7.0.4",
"identity-obj-proxy": "3.0.0",
"jest": "28.1.3",
"reactifex": "1.1.1",
"webpack-cli": "4.10.0"
Expand Down
40 changes: 40 additions & 0 deletions src/core/tests/Main.test.jsx
01001110J marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import React from 'react';
import { render, screen, act } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import '@testing-library/jest-dom';

import Main from '../Main';

jest.mock('../../views/ClassRoster', () => () => <div>Mocked ClassRoster Component</div>);
jest.mock('../../views/LabSummary', () => () => <div>Mocked LabSummary Component</div>);
jest.mock('../../views/LabDetails', () => () => <div>Mocked LabDetails Component</div>);

jest.mock('constants', () => ({
01001110J marked this conversation as resolved.
Show resolved Hide resolved
mfeBaseUrl: '/base-url',
}));

describe('Main Component', () => {
it('renders ClassRoster component by default', async () => {
await act(async () => {
render(
<MemoryRouter initialEntries={['/base-url']}>
<Main />
</MemoryRouter>,
);
});

expect(screen.getByText('Mocked ClassRoster Component')).toBeInTheDocument();
});

it('redirects to ClassRoster component when navigating to an unknown route', async () => {
await act(async () => {
render(
<MemoryRouter initialEntries={['/unknown-route']}>
<Main />
</MemoryRouter>,
);
});

expect(screen.getByText('Mocked ClassRoster Component')).toBeInTheDocument();
});
});
19 changes: 11 additions & 8 deletions src/helpers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,18 @@
* @returns {string} - String with Datetime in human readable format
*/
const formatUnixTimestamp = (timeStamp) => {
if (!timeStamp && typeof typestamp !== 'string') {
if (!timeStamp || Number.isNaN(Number(timeStamp))) {
return 'N/A';
}

const date = new Date(timeStamp * 1000);
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const year = date.getFullYear();

let hours = date.getHours();
const minutes = String(date.getMinutes()).padStart(2, '0');
const month = String(date.getUTCMonth() + 1).padStart(2, '0');
const day = String(date.getUTCDate()).padStart(2, '0');
const year = date.getUTCFullYear();
let hours = date.getUTCHours();
const minutes = String(date.getUTCMinutes()).padStart(2, '0');
const amPm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12 || 12; // Convert 0 to 12
hours = hours % 12 || 12;

return `${month}/${day}/${year} ${hours}:${minutes} ${amPm}`;
};
Expand Down Expand Up @@ -54,6 +53,10 @@ const formatTime = (time) => {
if (!time || typeof time !== 'string') {
return 'N/A';
}
const match = time.match(/\d+/);
if (!match) {
return 'N/A';
}
return new Date(parseInt(time.match(/\d+/)[0], 10))
.toLocaleDateString('en-US', {
month: '2-digit',
Expand Down
115 changes: 115 additions & 0 deletions src/helpers/tests/index.test.js
01001110J marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { eventManager, formatUnixTimestamp, formatTime } from '../index';

describe('Helper Functions', () => {
describe('formatUnixTimestamp', () => {
it('formats a valid UNIX timestamp correctly', () => {
const timestamp = 1672531199; // Corresponds to 12/31/2022 11:59 PM UTC
const formatted = formatUnixTimestamp(timestamp);

const expectedDate = new Date(timestamp * 1000).toLocaleString('en-US', {
timeZone: 'UTC',
month: '2-digit',
day: '2-digit',
year: 'numeric',
hour: 'numeric',
minute: '2-digit',
hour12: true,
});
expect(formatted).toBe(expectedDate.replace(',', ''));

const timestampPM = 1672531199; // 12/31/2022 11:59 PM UTC
const formattedPM = formatUnixTimestamp(timestampPM);
expect(formattedPM).toBe('12/31/2022 11:59 PM');

const timestampAM = 1672464000; // 12/31/2022 12:00 AM UTC
const formattedAM = formatUnixTimestamp(timestampAM);

const expectedAM = new Date(timestampAM * 1000).toLocaleString('en-US', {
timeZone: 'UTC',
month: '2-digit',
day: '2-digit',
year: 'numeric',
hour: 'numeric',
minute: '2-digit',
hour12: true,
});

expect(formattedAM).toBe(expectedAM.replace(',', ''));
});

it('returns "N/A" for invalid input', () => {
const formatted = formatUnixTimestamp('invalid');
expect(formatted).toBe('N/A');
});

it('returns "N/A" when input is null or undefined', () => {
expect(formatUnixTimestamp(null)).toBe('N/A');
expect(formatUnixTimestamp(undefined)).toBe('N/A');
});
});

describe('eventManager', () => {
it('executes the callback function correctly', async () => {
const mockCallback = jest.fn();
const managedEvent = eventManager(mockCallback);

await managedEvent();
expect(mockCallback).toHaveBeenCalled();
});

it('prevents multiple executions within a short time frame', async () => {
jest.useFakeTimers();
const mockCallback = jest.fn();
const managedEvent = eventManager(mockCallback);

await managedEvent();
await managedEvent();

expect(mockCallback).toHaveBeenCalledTimes(1);

jest.runAllTimers();
await managedEvent();

expect(mockCallback).toHaveBeenCalledTimes(2);
});

it('executes the callback function correctly', async () => {
const mockCallback = jest.fn();
const managedEvent = eventManager(mockCallback);

const mockEvent = { preventDefault: jest.fn() };

await managedEvent(mockEvent);

expect(mockEvent.preventDefault).toHaveBeenCalled();
expect(mockCallback).toHaveBeenCalled();
});
});

describe('formatTime', () => {
it('formats a valid timestamp string correctly', () => {
const timeString = '/Date(1672531199000)/'; // Corresponds to 12/31/2022 11:59 PM UTC
const formatted = formatTime(timeString);

const expectedDate = new Date(1672531199000).toLocaleDateString('en-US', {
month: '2-digit',
day: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
hour12: true,
}).replace(',', ' -');
expect(formatted).toBe(expectedDate);
});

it('returns "N/A" for invalid input', () => {
const formatted = formatTime('invalid');
expect(formatted).toBe('N/A');
});

it('returns "N/A" when input is null or undefined', () => {
expect(formatTime(null)).toBe('N/A');
expect(formatTime(undefined)).toBe('N/A');
});
});
});
1 change: 1 addition & 0 deletions src/index.jsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import React from 'react';
import 'core-js/stable';
import 'regenerator-runtime/runtime';
import { Container } from '@edx/paragon';
Expand Down
37 changes: 37 additions & 0 deletions src/shared/AlertMessage/tests/index.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import AlertMessage from '../index';

describe('AlertMessage Component', () => {
it('renders with default props', () => {
render(<AlertMessage heading="Test Heading" />);

expect(screen.getByText('Test Heading')).toBeInTheDocument();

const alert = screen.getByRole('alert');
expect(alert).toHaveClass('alert-danger');
});

it('renders with a custom variant, heading, and message', () => {
render(
<AlertMessage variant="warning" heading="Custom Heading" message="Custom message" />,
);

expect(screen.getByText('Custom Heading')).toBeInTheDocument();
expect(screen.getByText('Custom message')).toBeInTheDocument();

const alert = screen.getByRole('alert');
expect(alert).toHaveClass('alert-warning');
});

it('renders children correctly', () => {
render(
<AlertMessage heading="Test Heading">
<button type="button">Click me</button>
</AlertMessage>,
);

expect(screen.getByRole('button', { name: 'Click me' })).toBeInTheDocument();
});
});
2 changes: 1 addition & 1 deletion src/shared/DashboardLaunchButton/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Button } from 'react-paragon-topaz';

import AlertMessage from 'shared/AlertMessage';
import { skillableUrl, defaultErrorMessage } from 'constants';
import { eventManager } from 'helpers';
import { eventManager } from '../../helpers';

import './index.scss';

Expand Down
89 changes: 89 additions & 0 deletions src/shared/DashboardLaunchButton/tests/index.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import React from 'react';
import {
render,
screen,
fireEvent,
waitFor,
} from '@testing-library/react';
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
import DashboardLaunchButton from '../index';
import '@testing-library/jest-dom';

jest.mock('@edx/frontend-platform/auth', () => ({
getAuthenticatedHttpClient: jest.fn(),
}));
jest.mock('@edx/frontend-platform/logging', () => ({
logError: jest.fn(),
}));
jest.mock('shared/AlertMessage', () => () => <div>Mocked AlertMessage</div>);

const mockPost = jest.fn();
const mockCourseId = 'course-v1:edX+DemoX+Demo_Course';

describe('DashboardLaunchButton Component', () => {
beforeEach(() => {
getAuthenticatedHttpClient.mockReturnValue({ post: mockPost });
jest.clearAllMocks();
});

it('renders the component correctly with the given title', () => {
render(<DashboardLaunchButton courseId={mockCourseId} title="Test Title" />);
expect(screen.getByText('Test Title')).toBeInTheDocument();
});

it('does not show the button initially if is_ccx_course is false', async () => {
mockPost.mockResolvedValueOnce({ data: { is_ccx_course: false } });

render(<DashboardLaunchButton courseId={mockCourseId} title="Test Title" />);

await waitFor(() => {
expect(screen.queryByRole('button', { name: /Go To Instructor Dashboard/i })).not.toBeInTheDocument();
});
});

it('shows the button if is_ccx_course is true', async () => {
mockPost.mockResolvedValueOnce({ data: { is_ccx_course: true } });

render(<DashboardLaunchButton courseId={mockCourseId} title="Test Title" />);

await waitFor(() => {
expect(screen.getByRole('button', { name: /Go To Instructor Dashboard/i })).toBeInTheDocument();
});
});

it('handles button click and opens the dashboard URL if present', async () => {
mockPost.mockResolvedValueOnce({ data: { is_ccx_course: true } });
mockPost.mockResolvedValueOnce({ data: { url: 'https://example.com/dashboard' } });

render(<DashboardLaunchButton courseId={mockCourseId} title="Test Title" />);

await waitFor(() => {
expect(screen.getByRole('button', { name: /Go To Instructor Dashboard/i })).toBeInTheDocument();
});

window.open = jest.fn();

fireEvent.click(screen.getByRole('button', { name: /Go To Instructor Dashboard/i }));

await waitFor(() => {
expect(window.open).toHaveBeenCalledWith('https://example.com/dashboard', '_blank', 'noopener,noreferrer');
});
});

it('handles error when button is clicked and no URL is present', async () => {
mockPost.mockResolvedValueOnce({ data: { is_ccx_course: true } });
mockPost.mockResolvedValueOnce({ data: { url: '', error: 'Error message' } });

render(<DashboardLaunchButton courseId={mockCourseId} title="Test Title" />);

await waitFor(() => {
expect(screen.getByRole('button', { name: /Go To Instructor Dashboard/i })).toBeInTheDocument();
});

fireEvent.click(screen.getByRole('button', { name: /Go To Instructor Dashboard/i }));

await waitFor(() => {
expect(screen.getByText('Mocked AlertMessage')).toBeInTheDocument();
});
});
});
Loading
Loading