Skip to content

Commit

Permalink
DESENG-483: Test cases for FormCAC and Poll Widget View
Browse files Browse the repository at this point in the history
  • Loading branch information
ratheesh-aot committed Feb 22, 2024
1 parent ba96181 commit 517a7b5
Show file tree
Hide file tree
Showing 4 changed files with 233 additions and 0 deletions.
1 change: 1 addition & 0 deletions met-web/__mocks__/fileMock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default 'mock-file-stub';
1 change: 1 addition & 0 deletions met-web/jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ const config: Config.InitialOptions = {
'react-dnd-html5-backend': 'react-dnd-html5-backend-cjs',
'dnd-core': 'dnd-core-cjs',
'\\.(css|scss)$': '<rootDir>/tests/unit/components/styleMock.tsx',
"\\.(jpg|jpeg|png|gif|webp|svg)$": "<rootDir>/__mocks__/fileMock.ts",
},

// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
Expand Down
105 changes: 105 additions & 0 deletions met-web/tests/unit/components/FormCAC/FormCAC.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import React, { ReactNode } from 'react';
import { render, waitFor, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import { Form } from 'components/FormCAC/Form';
import { BrowserRouter as Router } from 'react-router-dom';
import { FormContext } from 'components/FormCAC/FormContext';

jest.mock('@mui/lab/TabContext/TabContext', () => {
// Create a mock component
return {
__esModule: true,
default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
};
});

jest.mock('@mui/lab/TabPanel/TabPanel', () => {
// Create a mock component
return {
__esModule: true,
default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
};
});

jest.mock('@mui/material', () => ({
...jest.requireActual('@mui/material'),
Link: ({ children }: { children: ReactNode }) => {
return <a>{children}</a>;
},
}));
// Mock hooks and services
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: () => jest.fn(),
useParams: () => ({
widgetId: '1',
engagementId: '1',
}),
}));

jest.mock('react-redux', () => ({
useDispatch: () => jest.fn(),
}));

const mockFormSubmissionData = {
understand: true,
termsOfReference: true,
firstName: 'John',
lastName: 'Doe',
city: 'New York',
email: '[email protected]',
};

const mockFormSubmission = {
tabValue: 1,
loading: false,
setTabValue: jest.fn(),
formSubmission: mockFormSubmissionData,
setFormSubmission: jest.fn(),
submitting: false,
setSubmitting: jest.fn(),
consentMessage: '',
};

describe('FormContextProvider Component Tests', () => {
const renderForm = () => {
render(
<Router>
<FormContext.Provider value={mockFormSubmission}>
<Form />
</FormContext.Provider>
</Router>,
);
};

test('loads and displays data correctly', async () => {
renderForm();

await waitFor(() => {
expect(screen.getByText('Community Advisory Committee')).toBeInTheDocument();
expect(screen.getByText('Learn about and sign up for a Community Advisory Committee')).toBeInTheDocument();
});
});

test('loads and displays two tabs correctly', async () => {
renderForm();

await waitFor(() => {
expect(screen.getByText('Information')).toBeInTheDocument();
expect(screen.getByText('You and Your Community')).toBeInTheDocument();
});
});

test('loads and displays form fields for tabs correctly', async () => {
renderForm();

await waitFor(() => {
expect(screen.getByText('First Name')).toBeInTheDocument();
expect(screen.getByText('Last Name')).toBeInTheDocument();
expect(screen.getByText('City')).toBeInTheDocument();
expect(screen.getByText('Email')).toBeInTheDocument();
expect(screen.getByText('Next')).toBeInTheDocument();
expect(screen.getByText('Submit')).toBeInTheDocument();
});
});
});
126 changes: 126 additions & 0 deletions met-web/tests/unit/components/widgets/PollWidgetView.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import React from 'react';
import { act, render, waitFor, fireEvent, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import PollWidgetView from 'components/engagement/view/widgets/Poll/PollWidgetView';
import * as widgetService from 'services/widgetService/PollService';
import * as notificationService from 'services/notificationService/notificationSlice';
import * as reactRedux from 'react-redux';

// Mock for useDispatch
jest.spyOn(reactRedux, 'useDispatch').mockImplementation(() => jest.fn());

// Mock for useSubmittedPolls
jest.mock('hooks', () => ({
// mock useAppSelector
useAppSelector: (callback: any) =>
callback({
user: {
authentication: {
authenticated: false,
},
},
}),
useAppDispatch: () => jest.fn(),
useSubmittedPolls: () => ({
getSubmittedPolls: jest.fn().mockReturnValue([]),
addSubmittedPoll: jest.fn(),
}),
}));

jest.mock('services/widgetService/PollService', () => ({
fetchPollWidgets: jest.fn(),
postPollResponse: jest.fn(),
}));

jest.mock('services/notificationService/notificationSlice', () => ({
openNotification: jest.fn(),
}));

describe('PollWidgetView Component Tests', () => {
const widget = {
id: 1,
title: 'Sample Poll',
widget_type_id: 10,
engagement_id: 1,
items: [],
};

const mockPoll = {
id: 1,
widget_id: 1,
engagement_id: 1,
title: 'Test Poll',
description: 'Description',
status: 'active',
answers: [
{ id: 1, answer_text: 'Option 1' },
{ id: 2, answer_text: 'Option 2' },
],
};

beforeEach(() => {
jest.spyOn(widgetService, 'fetchPollWidgets').mockReturnValue(Promise.resolve([mockPoll]));
});

test('renders poll details on successful data fetch', async () => {
await act(async () => {
render(<PollWidgetView widget={widget} />);
});

await waitFor(() => {
expect(screen.getByText(mockPoll.title)).toBeInTheDocument();
expect(screen.getByText(mockPoll.description)).toBeInTheDocument();
expect(screen.getByText(mockPoll.answers[0].answer_text)).toBeInTheDocument();
expect(screen.getByText('Submit')).toBeInTheDocument();
});
});

test('displays error notification on fetch failure', async () => {
jest.spyOn(widgetService, 'fetchPollWidgets').mockRejectedValue(new Error('Fetch Error'));
await act(async () => {
render(<PollWidgetView widget={widget} />);
});

await waitFor(() => {
expect(notificationService.openNotification).toHaveBeenCalledWith({
severity: 'error',
text: 'Error occurred while fetching Engagement widgets information',
});
});
});

test('submits poll response and displays success message', async () => {
jest.spyOn(widgetService, 'postPollResponse').mockResolvedValue({ selected_answer_id: '1' });
await act(async () => {
render(<PollWidgetView widget={widget} />);
});

const optionRadioButton = screen.getByLabelText(mockPoll.answers[0].answer_text);
fireEvent.click(optionRadioButton);

expect(optionRadioButton).toBeChecked();

fireEvent.click(screen.getByText('Submit'));
await waitFor(() => {
expect(widgetService.postPollResponse).toHaveBeenCalled();
expect(screen.getByText('Thank you for the response.')).toBeInTheDocument();
});
});

test('displays error message on submission failure', async () => {
jest.spyOn(widgetService, 'postPollResponse').mockRejectedValue({
response: { status: 400 },
});
await act(async () => {
render(<PollWidgetView widget={widget} />);
});

const optionRadioButton = screen.getByLabelText(mockPoll.answers[0].answer_text);
fireEvent.click(optionRadioButton);

fireEvent.click(screen.getByText('Submit'));
await waitFor(() => {
expect(screen.getByText('An error occurred.')).toBeInTheDocument();
});
});
});

0 comments on commit 517a7b5

Please sign in to comment.