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

Improved Code Coverage of UserListCard.tsx #3230

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Empty file.
152 changes: 139 additions & 13 deletions src/components/UserListCard/UserListCard.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,40 @@
import React from 'react';
import { render, screen, act } from '@testing-library/react';
import { render, screen, waitFor } from '@testing-library/react';
import { MockedProvider } from '@apollo/react-testing';
import userEvent from '@testing-library/user-event';
import { I18nextProvider } from 'react-i18next';
import { toast } from 'react-toastify';

import UserListCard from './UserListCard';
import { ADD_ADMIN_MUTATION } from 'GraphQl/Mutations/mutations';
import i18nForTest from 'utils/i18nForTest';
import { BrowserRouter } from 'react-router-dom';
import { StaticMockLink } from 'utils/StaticMockLink';
import { vi, describe, it, beforeEach } from 'vitest';
import { vi, describe, beforeEach, afterEach } from 'vitest';

// Mock modules
vi.mock('react-toastify', () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
},
}));

vi.mock('react-router-dom', async () => {
const actual = await vi.importActual('react-router-dom');
return {
...actual,
useParams: () => ({
orgId: '554',
}),
};
});

const MOCKS = [
{
request: {
query: ADD_ADMIN_MUTATION,
variables: { userid: '784', orgid: '554' },
variables: { userid: '456', orgid: '554' },
},
result: {
data: {
Expand All @@ -28,18 +47,41 @@ const MOCKS = [
},
},
];
const link = new StaticMockLink(MOCKS, true);

async function wait(ms = 100): Promise<void> {
await act(() => new Promise((resolve) => setTimeout(resolve, ms)));
}
const ERROR_MOCKS = [
{
request: {
query: ADD_ADMIN_MUTATION,
variables: { userid: '456', orgid: '554' },
},
error: new Error('An error occurred'),
},
];

const link = new StaticMockLink(MOCKS, true);
const errorLink = new StaticMockLink(ERROR_MOCKS, true);

describe('Testing User List Card', () => {
beforeEach(() => {
vi.spyOn(global, 'alert').mockImplementation(() => {});
Sriijannn marked this conversation as resolved.
Show resolved Hide resolved
vi.spyOn(window, 'location', 'get').mockReturnValue({
...window.location,
reload: vi.fn(),
});
Object.defineProperty(window, 'location', {
writable: true,
value: {
...window.location,
reload: vi.fn(), // Mock the reload function
},
});
});

afterEach(() => {
vi.clearAllMocks();
});

it('Should render props and text elements test for the page component', async () => {
test('Should show success toast and reload page after successful mutation', async () => {
const props = {
id: '456',
};
Expand All @@ -54,11 +96,59 @@ describe('Testing User List Card', () => {
</MockedProvider>,
);

await wait();
userEvent.click(screen.getByText(/Add Admin/i));
const button = screen.getByText(/Add Admin/i);
await userEvent.click(button);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(toast.success).toHaveBeenCalled();

await new Promise((resolve) => setTimeout(resolve, 2100));
Sriijannn marked this conversation as resolved.
Show resolved Hide resolved
expect(window.location.reload).toHaveBeenCalled();
});

test('Should show error toast when mutation fails', async () => {
const props = {
id: '456',
};

render(
<MockedProvider addTypename={false} link={errorLink}>
<BrowserRouter>
<I18nextProvider i18n={i18nForTest}>
<UserListCard key={123} {...props} />
</I18nextProvider>
</BrowserRouter>
</MockedProvider>,
);

const button = screen.getByText(/Add Admin/i);
await userEvent.click(button);

await new Promise((resolve) => setTimeout(resolve, 0));
expect(toast.error).toHaveBeenCalled();
});

it('Should render text elements when props value is not passed', async () => {
test('Should render button with correct styling', () => {
const props = {
id: '456',
key: 1,
};

render(
<MockedProvider mocks={[]} addTypename={false}>
<BrowserRouter>
<I18nextProvider i18n={i18nForTest}>
<UserListCard {...props} />
</I18nextProvider>
</BrowserRouter>
</MockedProvider>,
);

const button = screen.getByRole('button', { name: /Add Admin/i });
expect(button).toBeInTheDocument();
expect(button.className).toContain('memberfontcreatedbtn');
});

test('Should handle translations and URL parameters correctly', async () => {
const props = {
id: '456',
};
Expand All @@ -73,7 +163,43 @@ describe('Testing User List Card', () => {
</MockedProvider>,
);

await wait();
userEvent.click(screen.getByText(/Add Admin/i));
const button = screen.getByText(/Add Admin/i);
expect(button).toBeInTheDocument();

await userEvent.click(button);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(toast.success).toHaveBeenCalled();
});

test('Should display success toast and reload page after successful mutation', async () => {
const props = {
id: '456',
};

render(
<MockedProvider addTypename={false} mocks={MOCKS}>
<BrowserRouter>
<I18nextProvider i18n={i18nForTest}>
<UserListCard key={123} {...props} />
</I18nextProvider>
</BrowserRouter>
</MockedProvider>,
);

const button = screen.getByText(/Add Admin/i);
await userEvent.click(button);

// Wait for the toast success to be called
await waitFor(() => {
expect(toast.success).toHaveBeenCalledWith('User is added as admin.');
});

// Wait for the page reload to be triggered
await waitFor(
() => {
expect(window.location.reload).toHaveBeenCalled();
},
{ timeout: 5000 },
);
});
});
2 changes: 0 additions & 2 deletions src/components/UserListCard/UserListCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,13 @@ function userListCard(props: InterfaceUserListCardProps): JSX.Element {
},
});

/* istanbul ignore next */
if (data) {
toast.success(t('addedAsAdmin') as string);
setTimeout(() => {
window.location.reload();
}, 2000);
}
} catch (error: unknown) {
/* istanbul ignore next */
errorHandler(t, error);
}
};
Expand Down
Loading