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

Fixed error message in PostCard.tsx #3152

Merged
Merged
Show file tree
Hide file tree
Changes from 6 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
4 changes: 3 additions & 1 deletion public/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -1092,7 +1092,9 @@
"comments": "Comments",
"viewPost": "View Post",
"editPost": "Edit Post",
"postedOn": "Posted on {{date}}"
"postedOn": "Posted on {{date}}",
"emptyCommentError": "Please enter a comment before submitting.",
"unexpectedError": "An unexpected error occurred. Please try again."
},
"home": {
"posts": "Posts",
Expand Down
4 changes: 3 additions & 1 deletion public/locales/fr/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -1052,7 +1052,9 @@
"comments": "commentaires",
"viewPost": "Voir le message",
"editPost": "Modifier le message",
"postedOn": "Publié le {{date}}"
"postedOn": "Publié le {{date}}",
"emptyCommentError": "Veuillez saisir un commentaire avant de soumettre.",
"unexpectedError": "Une erreur inattendue s'est produite. Veuillez réessayer."
},
"home": {
"posts": "Des postes",
Expand Down
4 changes: 3 additions & 1 deletion public/locales/hi/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -1052,7 +1052,9 @@
"comments": "टिप्पणियाँ",
"viewPost": "पोस्ट देखें",
"editPost": "पोस्ट संपादित करें",
"postedOn": "{{date}} को पोस्ट किया गया"
"postedOn": "{{date}} को पोस्ट किया गया",
"emptyCommentError": "कृपया टिप्पणी करने से पहले एक टिप्पणी दर्ज करें।",
"unexpectedError": "एक अप्रत्याशित त्रुटि हुई। कृपया फिर से प्रयास करें।"
},
"home": {
"title": "पदों",
Expand Down
4 changes: 3 additions & 1 deletion public/locales/sp/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -1053,7 +1053,9 @@
"comments": "Comentarios",
"viewPost": "Ver publicación",
"editPost": "Editar publicación",
"postedOn": "Publicado el {{date}}"
"postedOn": "Publicado el {{date}}",
"emptyCommentError": "Por favor ingrese un comentario antes de enviarlo.",
"unexpectedError": "Ocurrió un error inesperado. Por favor, inténtelo de nuevo."
},
"home": {
"posts": "Publicaciones",
Expand Down
4 changes: 3 additions & 1 deletion public/locales/zh/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -1052,7 +1052,9 @@
"comments": "评论",
"viewPost": "查看帖子",
"editPost": "编辑帖子",
"postedOn": "发布于 {{date}}"
"postedOn": "发布于 {{date}}",
"emptyCommentError": "请在提交前输入评论。",
"unexpectedError": "发生了意外错误。请重试。"
},
"home": {
"title": "帖子",
Expand Down
115 changes: 114 additions & 1 deletion src/components/UserPortal/PostCard/PostCard.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { act } from 'react';
import { MockedProvider } from '@apollo/react-testing';
import { render, screen } from '@testing-library/react';
import { render, screen, waitFor } from '@testing-library/react';
import { I18nextProvider } from 'react-i18next';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
Expand Down Expand Up @@ -661,6 +661,119 @@ describe('Testing PostCard Component [User Portal]', () => {
await wait();
});

test('Comment validation displays an error toast when an empty comment is submitted', async () => {
console.log('Starting empty comment validation test');
Copy link
Contributor

@rishav-jha-mech rishav-jha-mech Jan 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Nivedita-Chhokar code rabbit is asking you to remove this line

console.log should not be here

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rishav-jha-mech Thank you for your review. I'll remove that line, but could you share your thoughts on the other suggestions made by Code Rabbit? Also, if you have any additional recommendations, I'd appreciate them.


const cardProps = {
id: '1',
userImage: 'image.png',
creator: {
firstName: 'test',
lastName: 'user',
email: '[email protected]',
id: '1',
},
postedAt: '',
image: 'testImage',
video: '',
text: 'This is post test text',
title: 'This is post test title',
likeCount: 1,
commentCount: 0,
comments: [],
likedBy: [
{
firstName: 'test',
lastName: 'user',
id: '1',
},
],
fetchPosts: vi.fn(),
};

expect(toast.error).toBeDefined();

render(
<MockedProvider addTypename={false} link={link}>
<BrowserRouter>
<Provider store={store}>
<I18nextProvider i18n={i18nForTest}>
<PostCard {...cardProps} />
</I18nextProvider>
</Provider>
</BrowserRouter>
</MockedProvider>,
);

userEvent.click(screen.getByTestId('viewPostBtn')); // Open the post view
userEvent.type(screen.getByTestId('commentInput'), ''); // Type an empty comment
userEvent.click(screen.getByTestId('createCommentBtn'));

await waitFor(() => {
expect(toast.error).toHaveBeenCalledWith(
i18nForTest.t('postCard.emptyCommentError'),
rishav-jha-mech marked this conversation as resolved.
Show resolved Hide resolved
);
});
});

test('Comment submission displays error toast when network error occurs', async () => {
const cardProps = {
id: '1',
userImage: 'image.png',
creator: {
firstName: 'test',
lastName: 'user',
email: '[email protected]',
id: '1',
},
postedAt: '',
image: 'testImage',
video: '',
text: 'This is post test text',
title: 'This is post test title',
likeCount: 1,
commentCount: 0,
comments: [],
likedBy: [
{
firstName: 'test',
lastName: 'user',
id: '1',
},
],
fetchPosts: vi.fn(),
};

const errorLink = new StaticMockLink([
{
request: {
query: CREATE_COMMENT_POST,
variables: {
postId: '1',
comment: 'test comment',
},
},
error: new Error('Network error'),
},
]);

render(
<MockedProvider link={errorLink}>
<PostCard {...cardProps} />
</MockedProvider>,
);
rishav-jha-mech marked this conversation as resolved.
Show resolved Hide resolved

userEvent.click(screen.getByTestId('viewPostBtn'));
userEvent.type(screen.getByTestId('commentInput'), 'test comment');
userEvent.click(screen.getByTestId('createCommentBtn'));

await waitFor(() => {
expect(toast.error).toHaveBeenCalledWith(
i18nForTest.t('postCard.unexpectedError'),
);
});
});

test(`Comment should be liked when like button is clicked`, async () => {
const cardProps = {
id: '1',
Expand Down
22 changes: 21 additions & 1 deletion src/components/UserPortal/PostCard/PostCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,12 @@
// Create a new comment
const createComment = async (): Promise<void> => {
try {
// Ensure the input is not empty
if (!commentInput.trim()) {
toast.error(t('emptyCommentError'));
return;
}

const { data: createEventData } = await create({
variables: {
postId: props.id,
Expand Down Expand Up @@ -225,7 +231,21 @@
setComments([...comments, newComment]);
}
} catch (error: unknown) {
errorHandler(t, error);
// Handle errors
// Log error with context for debugging
console.error('Error creating comment:', error);

// Show user-friendly translated message based on error type
if (error instanceof Error) {
const isValidationError = error.message.includes(
'Comment validation failed',
);
toast.error(
isValidationError ? t('emptyCommentError') : t('unexpectedError'),
);
} else {
toast.error(t('unexpectedError'));

Check warning on line 247 in src/components/UserPortal/PostCard/PostCard.tsx

View check run for this annotation

Codecov / codecov/patch

src/components/UserPortal/PostCard/PostCard.tsx#L247

Added line #L247 was not covered by tests
}
}
};

Expand Down
Loading