Skip to content

Commit

Permalink
[FIX] Improve code coverage of `src/components/UserPortal/StartPostMo…
Browse files Browse the repository at this point in the history
…dal/StartPostModal.spec.tsx` (#3099)

* improve code coverage

* Update UserNavbar.tsx

* Update UserNavbar.tsx

* Update UserNavbar.tsx
  • Loading branch information
hustlernik authored Dec 31, 2024
1 parent 04d773a commit b43b774
Show file tree
Hide file tree
Showing 2 changed files with 112 additions and 30 deletions.
139 changes: 111 additions & 28 deletions src/components/UserPortal/StartPostModal/StartPostModal.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,12 @@ import i18nForTest from 'utils/i18nForTest';
import StartPostModal from './StartPostModal';
import { vi } from 'vitest';

/**
* Unit tests for StartPostModal component:
*
* 1. **Rendering StartPostModal**: Verifies that the modal renders correctly when the `show` prop is set to `true`.
* 2. **Invalid post submission**: Ensures that when the post body is empty, an error toast is shown with the appropriate message ("Can't create a post with an empty body").
* 3. **Valid post submission**: Checks that a post with valid text triggers an info toast, and simulates the creation of a post with the message "Processing your post. Please wait."
* 4. **User image null**: Confirms that when the user image is null, a default image is displayed instead.
* 5. **User image not null**: Verifies that when the user image is provided, the correct user image is shown.
*
* Mocked GraphQL mutation (`CREATE_POST_MUTATION`) and toast notifications are used to simulate the post creation process.
* The `renderStartPostModal` function is used to render the modal with different user states and input values.
*/

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

Expand Down Expand Up @@ -60,6 +48,7 @@ const link = new StaticMockLink(MOCKS, true);

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

async function wait(ms = 100): Promise<void> {
Expand All @@ -73,16 +62,20 @@ async function wait(ms = 100): Promise<void> {
const renderStartPostModal = (
visibility: boolean,
image: string | null,
img: string | null = null,
onHide: () => void = vi.fn(),
fetchPosts: () => void = vi.fn(),
customLink: StaticMockLink = link,
): RenderResult => {
const cardProps = {
show: visibility,
onHide: vi.fn(),
fetchPosts: vi.fn(),
onHide,
fetchPosts,
userData: {
user: {
__typename: 'User',
_id: '123',
image: image,
image,
firstName: 'Glen',
lastName: 'dsza',
email: '[email protected]',
Expand All @@ -109,11 +102,11 @@ const renderStartPostModal = (
},
},
organizationId: '123',
img: '',
img,
};

return render(
<MockedProvider addTypename={false} link={link}>
<MockedProvider addTypename={false} link={customLink}>
<BrowserRouter>
<Provider store={store}>
<I18nextProvider i18n={i18nForTest}>
Expand All @@ -126,13 +119,8 @@ const renderStartPostModal = (
};

describe('Testing StartPostModal Component: User Portal', () => {
afterAll(() => {
vi.clearAllMocks();
});

it('Check if StartPostModal renders properly', async () => {
renderStartPostModal(true, null);

const modal = await screen.findByTestId('startPostModal');
expect(modal).toBeInTheDocument();
});
Expand All @@ -158,14 +146,10 @@ describe('Testing StartPostModal Component: User Portal', () => {

userEvent.click(screen.getByTestId('createPostBtn'));

expect(toast.error).not.toHaveBeenCalledWith();
expect(toast.error).not.toHaveBeenCalled();
expect(toast.info).toHaveBeenCalledWith(
'Processing your post. Please wait.',
);
// await wait();
// expect(toast.success).toBeCalledWith(
// 'Your post is now visible in the feed.',
// );
});

it('If user image is null then default image should be shown', async () => {
Expand All @@ -186,4 +170,103 @@ describe('Testing StartPostModal Component: User Portal', () => {
const userImage = screen.getByTestId('userImage');
expect(userImage).toHaveAttribute('src', 'image.png');
});

it('should clear post content and hide modal when close button is clicked', async () => {
const onHideMock = vi.fn();
renderStartPostModal(true, null, null, onHideMock);
await wait();

const input = screen.getByTestId('postInput');
userEvent.type(input, 'Test content');

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

expect(onHideMock).toHaveBeenCalled();
expect(input).toHaveValue('');
});

it('should handle successful post creation', async () => {
const fetchPostsMock = vi.fn();
const onHideMock = vi.fn();
const successMocks = [
{
request: {
query: CREATE_POST_MUTATION,
variables: {
title: '',
text: 'Test content',
organizationId: '123',
file: null,
},
},
result: {
data: {
createPost: {
_id: '456',
},
},
},
},
];
const customLink = new StaticMockLink(successMocks, true);

renderStartPostModal(
true,
null,
null,
onHideMock,
fetchPostsMock,
customLink,
);
await wait();

userEvent.type(screen.getByTestId('postInput'), 'Test content');
userEvent.click(screen.getByTestId('createPostBtn'));

await wait();

expect(toast.dismiss).toHaveBeenCalled();
expect(toast.success).toHaveBeenCalled();
expect(fetchPostsMock).toHaveBeenCalled();
expect(onHideMock).toHaveBeenCalled();
});

it('should handle failed post creation', async () => {
const errorMocks = [
{
request: {
query: CREATE_POST_MUTATION,
variables: {
title: '',
text: 'Test content',
organizationId: '123',
file: null,
},
},
error: new Error('Failed to create post'),
},
];
const customLink = new StaticMockLink(errorMocks, true);

renderStartPostModal(true, null, null, vi.fn(), vi.fn(), customLink);
await wait();

userEvent.type(screen.getByTestId('postInput'), 'Test content');
userEvent.click(screen.getByTestId('createPostBtn'));

await wait();

expect(toast.error).toHaveBeenCalled();
});

it('should display preview image when provided', async () => {
const previewImage = 'preview.jpg';
renderStartPostModal(true, null, previewImage);
await wait();

const image = screen.getByAltText('Post Image Preview');
expect(image).toBeInTheDocument();
expect(image).toHaveAttribute('src', previewImage);
});
});
3 changes: 1 addition & 2 deletions src/components/UserPortal/StartPostModal/StartPostModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,15 +90,14 @@ const startPostModal = ({
file: img,
},
});
/* istanbul ignore next */

if (data) {
toast.dismiss();
toast.success(t('postNowVisibleInFeed') as string);
fetchPosts();
handleHide();
}
} catch (error: unknown) {
/* istanbul ignore next */
errorHandler(t, error);
}
};
Expand Down

0 comments on commit b43b774

Please sign in to comment.