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 12 commits into
base: develop-postgres
Choose a base branch
from
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,108 @@
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
NishantSinghhhhh marked this conversation as resolved.
Show resolved Hide resolved
*/

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 +1538,42 @@ 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();
window.HTMLElement.prototype.scrollIntoView = vi.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,
];

// Optional: Use beforeEach if there are other setups like clearing localStorage
beforeEach(() => {
// Add any setup you need before each test, e.g., reset state
setItem('userId', '1');
});
NishantSinghhhhh marked this conversation as resolved.
Show resolved Hide resolved

test('Screen should be rendered properly', async () => {
render(
<MockedProvider addTypename={false} mocks={mock}>
<BrowserRouter>
Expand All @@ -1512,18 +1588,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 +1602,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 +1626,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 +1641,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 +1663,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 +1695,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 +1709,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();
});
});
2 changes: 2 additions & 0 deletions vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
import { nodePolyfills } from 'vite-plugin-node-polyfills';
import tsconfigPaths from 'vite-tsconfig-paths';
import svgr from 'vite-plugin-svgr';

export default defineConfig({
plugins: [
react(),
[svgr()],
nodePolyfills({
include: ['events'],
}),
Expand Down
Loading