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

added vitest to chat.jsx #2649

Open
wants to merge 6 commits into
base: develop-postgres
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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
13 changes: 7 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@
"postcss-modules": "^6.0.0",
"sass": "^1.80.7",
"tsx": "^4.19.1",
"vite-plugin-svgr": "^4.2.0",
"vite-plugin-svgr": "^4.3.0",
"vitest": "^2.1.5",
"whatwg-fetch": "^3.6.20"
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,27 +1,112 @@
import React from 'react';
import {
act,
fireEvent,
render,
fireEvent,
screen,
waitFor,
act,
} from '@testing-library/react';
import { MockedProvider } from '@apollo/react-testing';
import { I18nextProvider } from 'react-i18next';

import {
USERS_CONNECTION_LIST,
USER_JOINED_ORGANIZATIONS,
} from 'GraphQl/Queries/Queries';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { expect, describe, test, vi } from 'vitest';
import { store } from 'state/store';
import i18nForTest from 'utils/i18nForTest';
import { I18nextProvider } from 'react-i18next';
import Chat from './Chat';
import useLocalStorage from 'utils/useLocalstorage';
import {
USERS_CONNECTION_LIST,
USER_JOINED_ORGANIZATIONS,
} from 'GraphQl/Queries/Queries';
import { MESSAGE_SENT_TO_CHAT } from 'GraphQl/Mutations/OrganizationMutations';
import { CHATS_LIST, CHAT_BY_ID } from 'GraphQl/Queries/PlugInQueries';
import useLocalStorage from 'utils/useLocalstorage';

/**
# Testing Chat Screen [User Portal]

**Description**:
This script contains a suite of tests for the `Chat` component in the User Portal. It validates the rendering, functionality, and responsiveness of the `Chat` screen, including direct and group chat creation, sidebar behavior, and mobile view compatibility.

---

## Global Setup
- **Mocks**:
- `scrollIntoView`: Prevents errors during testing.
- `matchMedia`: Mocks media query behaviors for responsiveness testing.

---

## Mock Data
- Combines multiple mock datasets:
- `USER_JOINED_ORG_MOCK`
- `GROUP_CHAT_BY_ID_QUERY_MOCK`
- `MESSAGE_SENT_TO_CHAT_MOCK`
- `CHAT_BY_ID_QUERY_MOCK`
- `CHATS_LIST_MOCK`
- `UserConnectionListMock`

---

## Test Initialization
- **Before Each Test**:
- Sets up local storage with a `userId` for testing purposes.

---

## Test Cases

1. **Rendering of the Chat Screen**
- Ensures the `Chat` screen renders correctly with all required elements.

2. **Selecting a Contact**
- Verifies that a user can select a contact from the contact list.

3. **Creating a New Direct Chat**
- Tests dropdown functionality.
- Validates the creation of a new direct chat and the presence of relevant UI elements.

4. **Creating a New Group Chat**
- Similar to the direct chat test but ensures the group chat creation workflow functions correctly.

5. **Sidebar Functionality**
- Tests the sidebar’s open/close behavior in desktop view.

6. **Responsive Sidebar for Mobile View**
- Simulates screen resizing to mobile dimensions (≤ 820px).
- Ensures the sidebar opens and closes correctly in mobile view.

---

## Helper Functions
- **`resizeWindow`**: Simulates screen resizing to test responsive behavior.

---

## Libraries and Tools
- **Testing Framework**: Vitest
- **Mocking**: Apollo’s `MockedProvider`
- **Routing**: React Router’s `BrowserRouter`
- **State Management**: Redux Provider
- **Internationalization**: I18next Provider
*/

vi.mock('../../../components/UserPortal/ChatRoom/ChatRoom', () => ({
default: () => <div data-testid="mocked-chat-room">Mocked ChatRoom</div>,
}));

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

async function wait(ms = 100): Promise<void> {
await act(() => {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
});
}
const { setItem } = useLocalStorage();

const USER_JOINED_ORG_MOCK = [
Expand Down Expand Up @@ -1457,47 +1542,45 @@ const GROUP_CHAT_BY_ID_QUERY_MOCK = [
},
];

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

async function wait(ms = 100): Promise<void> {
await act(() => {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
});
}

describe('Testing Chat Screen [User Portal]', () => {
window.HTMLElement.prototype.scrollIntoView = jest.fn();

Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation((query) => ({
value: vi.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // Deprecated
removeListener: jest.fn(), // Deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});

test('Screen should be rendered properly', async () => {
const mock = [
...USER_JOINED_ORG_MOCK,
...GROUP_CHAT_BY_ID_QUERY_MOCK,
...MESSAGE_SENT_TO_CHAT_MOCK,
...UserConnectionListMock,
...CHAT_BY_ID_QUERY_MOCK,
...CHATS_LIST_MOCK,
...UserConnectionListMock,
];
// Define mock data outside of tests to reuse
const mock = [
...USER_JOINED_ORG_MOCK,
...GROUP_CHAT_BY_ID_QUERY_MOCK,
...MESSAGE_SENT_TO_CHAT_MOCK,
...MESSAGE_SENT_TO_CHAT_MOCK,
...UserConnectionListMock,
...CHAT_BY_ID_QUERY_MOCK,
...CHATS_LIST_MOCK,
...UserConnectionListMock,
];

beforeEach(() => {
setItem('userId', '1');
vi.clearAllMocks();
localStorage.clear();
vi.resetModules();
});

afterEach(() => {
localStorage.clear();
});

test('Screen should be rendered properly', async () => {
render(
<MockedProvider addTypename={false} mocks={mock}>
<BrowserRouter>
Expand All @@ -1512,18 +1595,7 @@ describe('Testing Chat Screen [User Portal]', () => {
await wait();
});

test('User is able to select a contact', async () => {
const mock = [
...USER_JOINED_ORG_MOCK,
...GROUP_CHAT_BY_ID_QUERY_MOCK,
...MESSAGE_SENT_TO_CHAT_MOCK,
...MESSAGE_SENT_TO_CHAT_MOCK,
...UserConnectionListMock,
...CHAT_BY_ID_QUERY_MOCK,
...CHATS_LIST_MOCK,
...UserConnectionListMock,
];

it('User is able to select a contact', async () => {
render(
<MockedProvider addTypename={false} mocks={mock}>
<BrowserRouter>
Expand All @@ -1537,24 +1609,13 @@ describe('Testing Chat Screen [User Portal]', () => {
);

await wait();

expect(await screen.findByText('Messages')).toBeInTheDocument();

expect(
await screen.findByTestId('contactCardContainer'),
).toBeInTheDocument();
});

test('create new direct chat', async () => {
const mock = [
...USER_JOINED_ORG_MOCK,
...GROUP_CHAT_BY_ID_QUERY_MOCK,
...MESSAGE_SENT_TO_CHAT_MOCK,
...MESSAGE_SENT_TO_CHAT_MOCK,
...CHAT_BY_ID_QUERY_MOCK,
...CHATS_LIST_MOCK,
...UserConnectionListMock,
];
render(
<MockedProvider addTypename={false} mocks={mock}>
<BrowserRouter>
Expand All @@ -1572,6 +1633,7 @@ describe('Testing Chat Screen [User Portal]', () => {
const dropdown = await screen.findByTestId('dropdown');
expect(dropdown).toBeInTheDocument();
fireEvent.click(dropdown);

const newDirectChatBtn = await screen.findByTestId('newDirectChat');
expect(newDirectChatBtn).toBeInTheDocument();
fireEvent.click(newDirectChatBtn);
Expand All @@ -1586,16 +1648,6 @@ describe('Testing Chat Screen [User Portal]', () => {
});

test('create new group chat', async () => {
const mock = [
...USER_JOINED_ORG_MOCK,
...GROUP_CHAT_BY_ID_QUERY_MOCK,
...MESSAGE_SENT_TO_CHAT_MOCK,
...UserConnectionListMock,
...MESSAGE_SENT_TO_CHAT_MOCK,
...CHAT_BY_ID_QUERY_MOCK,
...CHATS_LIST_MOCK,
...UserConnectionListMock,
];
render(
<MockedProvider addTypename={false} mocks={mock}>
<BrowserRouter>
Expand All @@ -1618,25 +1670,14 @@ describe('Testing Chat Screen [User Portal]', () => {
expect(newGroupChatBtn).toBeInTheDocument();

fireEvent.click(newGroupChatBtn);

const closeButton = screen.getByRole('button', { name: /close/i });
expect(closeButton).toBeInTheDocument();

fireEvent.click(closeButton);
});

test('sidebar', async () => {
const mock = [
...USER_JOINED_ORG_MOCK,
...GROUP_CHAT_BY_ID_QUERY_MOCK,
...MESSAGE_SENT_TO_CHAT_MOCK,
...UserConnectionListMock,
...MESSAGE_SENT_TO_CHAT_MOCK,
...CHAT_BY_ID_QUERY_MOCK,
...CHATS_LIST_MOCK,
...UserConnectionListMock,
];
setItem('userId', '1');

render(
<MockedProvider addTypename={false} mocks={mock}>
<BrowserRouter>
Expand All @@ -1661,18 +1702,9 @@ describe('Testing Chat Screen [User Portal]', () => {
});

test('Testing sidebar when the screen size is less than or equal to 820px', async () => {
setItem('userId', '1');
const mock = [
...USER_JOINED_ORG_MOCK,
...GROUP_CHAT_BY_ID_QUERY_MOCK,
...MESSAGE_SENT_TO_CHAT_MOCK,
...UserConnectionListMock,
...MESSAGE_SENT_TO_CHAT_MOCK,
...CHAT_BY_ID_QUERY_MOCK,
...CHATS_LIST_MOCK,
...UserConnectionListMock,
];
// Resize window for mobile view (<= 820px)
resizeWindow(800);

render(
<MockedProvider addTypename={false} mocks={mock}>
<BrowserRouter>
Expand All @@ -1684,12 +1716,17 @@ describe('Testing Chat Screen [User Portal]', () => {
</BrowserRouter>
</MockedProvider>,
);
await wait();
expect(screen.getByText('My Organizations')).toBeInTheDocument();
expect(screen.getByText('Talawa User Portal')).toBeInTheDocument();

expect(await screen.findByTestId('openMenu')).toBeInTheDocument();
fireEvent.click(screen.getByTestId('openMenu'));
expect(await screen.findByTestId('closeMenu')).toBeInTheDocument();
await waitFor(() => {
expect(screen.getByText('My Organizations')).toBeInTheDocument();
expect(screen.getByText('Talawa User Portal')).toBeInTheDocument();
});

const openMenuBtn = await screen.findByTestId('openMenu');
expect(openMenuBtn).toBeInTheDocument();
fireEvent.click(openMenuBtn);

const closeMenuBtn = await screen.findByTestId('closeMenu');
expect(closeMenuBtn).toBeInTheDocument();
});
});
1 change: 1 addition & 0 deletions vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import svgrPlugin from 'vite-plugin-svgr';
export default defineConfig({
plugins: [
react(),
[svgr()],
nodePolyfills({
include: ['events'],
}),
Expand Down
Loading