-
-
Notifications
You must be signed in to change notification settings - Fork 811
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 in src/screens/Users/Users.tsx #3298
base: develop-postgres
Are you sure you want to change the base?
Improved Code Coverage in src/screens/Users/Users.tsx #3298
Conversation
WalkthroughThe pull request introduces comprehensive changes to the Users module, focusing on enhancing test coverage and mock data structures. The modifications span multiple files in the Changes
Assessment against linked issues
Suggested reviewers
Poem
Finishing Touches
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
Our Pull Request Approval ProcessThanks for contributing! Testing Your CodeRemember, your PRs won't be reviewed until these criteria are met:
Our policies make our code better. ReviewersDo not assign reviewers. Our Queue Monitors will review your PR and assign them.
Reviewing Your CodeYour reviewer(s) will have the following roles:
CONTRIBUTING.mdRead our CONTRIBUTING.md file. Most importantly:
Other
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🔭 Outside diff range comments (1)
src/screens/Users/UsersMocks.ts (1)
Line range hint
1-1386
: Critical: File exceeds maximum line count limit.The file is 1374 lines long, exceeding the maximum limit of 600 lines. Consider splitting the mock data into separate files:
- Create a directory
src/screens/Users/__mocks__/
- Split mocks by functionality (e.g.,
userMocks.ts
,searchMocks.ts
,paginationMocks.ts
)Example restructuring:
// src/screens/Users/__mocks__/userMocks.ts export const createAddress = {...} export const createCreator = {...} export const MOCK_USERS = [...] // src/screens/Users/__mocks__/searchMocks.ts import { MOCK_USERS } from './userMocks' export const EMPTY_MOCK_NEW = [...] export const MOCKS_NEW = [...] // src/screens/Users/__mocks__/paginationMocks.ts import { MOCK_USERS, MOCK_USERS2 } from './userMocks' export const MOCKS_NEW2 = [...] export const MOCKS_NEW3 = [...]
🧹 Nitpick comments (2)
src/screens/Users/Users.spec.tsx (1)
784-843
: Consider adding more assertions for sorting order.While the test verifies the presence of rows after sorting, it would be more robust to verify the actual sorting order by checking the dates or names of the displayed users.
const rowsNewest = await screen.findAllByRole('row'); -expect(rowsNewest.length).toBeGreaterThan(0); +// Verify sorting order by checking user creation dates +const dates = rowsNewest.slice(1).map(row => { + const user = MOCK_USERS.find(u => row.textContent?.includes(u.user.firstName)); + return new Date(user?.user.createdAt || ''); +}); +expect(dates).toEqual([...dates].sort((a, b) => b.getTime() - a.getTime()));src/screens/Users/UsersMocks.ts (1)
546-1187
: Consider using a mock data generator.Instead of manually defining large sets of mock users, consider using a library like
@faker-js/faker
to generate mock data dynamically. This would reduce file size and make the tests more maintainable.Example:
import { faker } from '@faker-js/faker'; const createMockUser = (id: number) => ({ user: { _id: `user${id}`, firstName: faker.person.firstName(), lastName: faker.person.lastName(), email: faker.internet.email(), createdAt: faker.date.recent().toISOString(), // ... other fields }, appUserProfile: { _id: `user${id}`, // ... other fields } }); export const MOCK_USERS = Array.from({ length: 3 }, (_, i) => createMockUser(i + 1));
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/screens/Users/Users.spec.tsx
(2 hunks)src/screens/Users/Users.tsx
(0 hunks)src/screens/Users/UsersMocks.ts
(1 hunks)
💤 Files with no reviewable changes (1)
- src/screens/Users/Users.tsx
🧰 Additional context used
🪛 GitHub Actions: PR Workflow
src/screens/Users/UsersMocks.ts
[error] 1-1374: File exceeds maximum line count limit of 600 lines (current: 1374 lines)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: Analyse Code With CodeQL (javascript)
🔇 Additional comments (2)
src/screens/Users/Users.spec.tsx (1)
734-782
: Well-structured test for search functionality!The test case thoroughly verifies both the presence of the "No results found" message and its content, which is a good practice for user feedback testing.
src/screens/Users/UsersMocks.ts (1)
526-544
: Great use of reusable mock objects!The
createAddress
andcreateCreator
objects help reduce duplication and improve maintainability.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
🔭 Outside diff range comments (2)
src/screens/Users/Users.tsx (1)
Line range hint
116-124
: Add missing dependencies to useEffect hook.The useEffect hook that manages loading state is missing dependencies. Add
isLoadingMore
to the dependency array to ensure the effect runs when this state changes.useEffect(() => { if (loading && isLoadingMore == false) { setIsLoading(true); } else { setIsLoading(false); } - }, [loading]); + }, [loading, isLoadingMore]);src/screens/Users/Users.spec.tsx (1)
Line range hint
37-43
: Replace fixed wait time with waitFor utility.Using a fixed wait time of 1000ms can make tests flaky. Use
waitFor
from @testing-library/react to wait for specific conditions instead.- async function wait(ms = 1000): Promise<void> { - await act(() => { - return new Promise((resolve) => { - setTimeout(resolve, ms); - }); - }); - } + import { waitFor } from '@testing-library/react';Example usage:
await waitFor(() => { expect(screen.getByTestId('users-list')).toBeInTheDocument(); });
🧹 Nitpick comments (1)
src/screens/Users/Users.spec.tsx (1)
830-831
: Use meaningful constants instead of magic numbers in tests.The test uses magic number 4 for row count assertion. Extract this into a named constant to improve test readability and maintainability.
+ const HEADER_ROW = 1; + const INITIAL_USER_COUNT = 3; + const EXPECTED_ROW_COUNT = HEADER_ROW + INITIAL_USER_COUNT; let rows = screen.getAllByRole('row'); - expect(rows.length).toBe(4); + expect(rows.length).toBe(EXPECTED_ROW_COUNT);
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/screens/Users/Users.spec.tsx
(2 hunks)src/screens/Users/Users.tsx
(1 hunks)src/screens/Users/UsersMocks.mocks.ts
(1 hunks)
🧰 Additional context used
🪛 GitHub Actions: PR Workflow
src/screens/Users/UsersMocks.mocks.ts
[error] 1-1355: File exceeds maximum line count limit of 600 lines (current: 1355 lines)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: Analyse Code With CodeQL (javascript)
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop-postgres #3298 +/- ##
=====================================================
+ Coverage 8.43% 89.84% +81.40%
=====================================================
Files 310 333 +23
Lines 8069 8587 +518
Branches 1792 1901 +109
=====================================================
+ Hits 681 7715 +7034
+ Misses 7311 610 -6701
- Partials 77 262 +185
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (4)
src/screens/Users/UsersMocks.mocks.ts (1)
37-72
: Rename MOCKS_NEW_2 to follow consistent naming convention.The mock array name
MOCKS_NEW_2
doesn't follow the same naming pattern as other mocks (MOCKS_NEW2
,MOCKS_NEW3
). Consider renaming it to maintain consistency.-export const MOCKS_NEW_2 = [ +export const MOCKS_NEW1 = [src/screens/Users/Organization.mocks.ts (2)
1-55
: Enhance interface definitions with documentation and validation.The TypeScript interfaces would benefit from:
- JSDoc comments explaining the purpose of each interface
- Optional properties where appropriate
- Stricter types for arrays (currently empty array literals)
+/** Address information for organizations and users */ interface InterfaceAddress { city: string; countryCode: string; - dependentLocality: string; + dependentLocality?: string; line1: string; - line2: string; + line2?: string; postalCode: string; sortingCode: string; state: string; } +/** Creator information for organizations */ interface InterfaceCreator { _id: string; firstName: string; lastName: string; image: string | null; email: string; createdAt: string; } +/** Organization information including address and creator */ interface InterfaceOrganization { // ... existing properties } +/** User information including organizations */ interface InterfaceUser { // ... existing properties - registeredEvents: []; - membershipRequests: []; + registeredEvents: unknown[]; + membershipRequests: unknown[]; organizationsBlockedBy: InterfaceOrganization[]; joinedOrganizations: InterfaceOrganization[]; }
236-282
: Improve the generateMockUser helper function.The function could be enhanced with:
- Default values for optional parameters
- Type validation for email format
- Reusable constants for repeated data
+const DEFAULT_ORGANIZATION = { + _id: 'xyz', + name: 'ABC', + image: null, + address: createAddress, + createdAt: '19/06/2022', + creator: createCreator, +}; const generateMockUser = ( id: string, firstName: string, lastName: string, email: string, createdAt: string, isSuperAdmin = false, + options = { + organizationsBlockedBy: [DEFAULT_ORGANIZATION], + joinedOrganizations: [{...DEFAULT_ORGANIZATION, _id: 'abc', name: 'Joined Organization 1'}], + } ): InterfaceMockUser => ({ // ... rest of the implementation using options });src/screens/Users/Users.spec.tsx (1)
783-839
: Enhance test coverage for sorting and pagination.The test suite could be improved by:
- Testing edge cases (e.g., sorting empty results)
- Verifying sort order with actual timestamps
- Adding error cases for failed API requests
Consider adding these test cases:
it('should maintain sort order when loading more users', async () => { // Test implementation }); it('should handle API errors during sorting', async () => { // Test implementation }); it('should reset pagination when changing sort order', async () => { // Test implementation });
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/screens/Users/Organization.mocks.ts
(1 hunks)src/screens/Users/User.mocks.ts
(3 hunks)src/screens/Users/Users.spec.tsx
(2 hunks)src/screens/Users/UsersMocks.mocks.ts
(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: Test Application
- GitHub Check: Analyse Code With CodeQL (javascript)
🔇 Additional comments (2)
src/screens/Users/User.mocks.ts (1)
44-44
: Standardize date formats across mock data.The file uses inconsistent date formats:
- ISO 8601:
2022-06-20T00:00:00.000Z
- DD/MM/YYYY:
20/06/2022
This inconsistency could lead to date parsing issues in tests.
Also applies to: 119-119
src/screens/Users/Users.spec.tsx (1)
733-781
: LGTM! Well-structured test for "No results found" scenario.The test case is well-organized with clear setup, action, and assertion phases.
@coderabbitai full review |
✅ Actions performedFull review triggered. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
♻️ Duplicate comments (2)
src/screens/Users/UsersMocks.mocks.ts (2)
37-72
:⚠️ Potential issueFix pagination logic in mock data to prevent inconsistent test results
As previously mentioned, the pagination logic in
MOCKS_NEW_2
may be incorrect. The second request slicesMOCK_USERS.slice(12, 24)
, but ifMOCK_USERS
has fewer than 24 users, this could lead to empty or inconsistent data in tests.Consider adjusting the slices to match the actual length of
MOCK_USERS
or dynamically determine the slice ranges based on the array's length to ensure accurate pagination in your tests.🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 37-37: src/screens/Users/UsersMocks.mocks.ts#L37
Added line #L37 was not covered by tests
152-234
:⚠️ Potential issueCorrect overlapping and duplicate slices in mock data
As previously noted, in
MOCKS_NEW3
, there are overlapping slices and duplicate requests:
- Lines 194 and 212 both use
users: MOCK_USERS2.slice(11, 15)
, leading to duplicate data in tests.- This may cause unexpected behavior or misleading test results.
Adjust the slice ranges to ensure proper pagination and avoid duplicates. For example:
- users: MOCK_USERS2.slice(11, 15), + users: MOCK_USERS2.slice(12, 16),Ensure that each slice is unique and aligns with your pagination logic.
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 152-152: src/screens/Users/UsersMocks.mocks.ts#L152
Added line #L152 was not covered by tests
🧹 Nitpick comments (4)
src/screens/Users/Users.tsx (2)
Line range hint
164-169
: Use React refs instead ofdocument.getElementById
Directly accessing DOM elements using
document.getElementById
is not recommended in React, as it bypasses the Virtual DOM and can lead to unexpected behavior. Consider usinguseRef
to access the input element, which aligns with React's best practices and improves code maintainability.Apply this diff to implement
useRef
:+ import React, { useEffect, useState, useRef } from 'react'; ... + const inputRef = useRef<HTMLInputElement>(null); ... const handleSearchByBtnClick = (): void => { - const inputElement = document.getElementById( - 'searchUsers', - ) as HTMLInputElement; - const inputValue = inputElement?.value || ''; + const inputValue = inputRef.current?.value || ''; handleSearch(inputValue); }; ... <Form.Control type="name" id="searchUsers" + ref={inputRef} className="bg-white" placeholder={t('enterName')} data-testid="searchByName" autoComplete="off" required onKeyUp={handleSearchByEnter} />
Line range hint
262-266
: SimplifyisLoading
state managementCurrently,
isLoading
is managed through auseEffect
, updating state based on other state variables. This can be simplified by derivingisLoading
directly fromloading
andisLoadingMore
, reducing complexity and potential synchronization issues.Apply this diff to simplify
isLoading
:- const [isLoading, setIsLoading] = useState(true); ... - useEffect(() => { - if (loading && isLoadingMore == false) { - setIsLoading(true); - } else { - setIsLoading(false); - } - }, [loading]); + const isLoading = loading && !isLoadingMore;src/screens/Users/User.mocks.ts (1)
44-44
: Standardize date formats across mock data.While changing to ISO 8601 format is good, there are inconsistent date formats in the mock data. Some dates use ISO 8601 (e.g., line 44) while others use 'DD/MM/YYYY' format (e.g., organization's createdAt).
Consider updating all date strings to use ISO 8601 format for consistency:
- createdAt: '20/06/2022', + createdAt: '2022-06-20T00:00:00.000Z',src/screens/Users/Users.spec.tsx (1)
783-839
: LGTM! Good coverage of sorting and loading functionality.The tests effectively verify sorting order changes and user loading behavior.
Consider adding these edge cases to strengthen the test suite:
- Test sorting with empty user list
- Test loading more users when there are exactly 12 users (edge of pagination)
- Test sorting after loading more users to ensure the entire dataset maintains order
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
src/screens/Users/Organization.mocks.ts
(1 hunks)src/screens/Users/User.mocks.ts
(3 hunks)src/screens/Users/Users.spec.tsx
(2 hunks)src/screens/Users/Users.tsx
(1 hunks)src/screens/Users/UsersMocks.mocks.ts
(1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
src/screens/Users/UsersMocks.mocks.ts
[warning] 8-8: src/screens/Users/UsersMocks.mocks.ts#L8
Added line #L8 was not covered by tests
[warning] 37-37: src/screens/Users/UsersMocks.mocks.ts#L37
Added line #L37 was not covered by tests
[warning] 74-74: src/screens/Users/UsersMocks.mocks.ts#L74
Added line #L74 was not covered by tests
[warning] 104-104: src/screens/Users/UsersMocks.mocks.ts#L104
Added line #L104 was not covered by tests
[warning] 152-152: src/screens/Users/UsersMocks.mocks.ts#L152
Added line #L152 was not covered by tests
src/screens/Users/Organization.mocks.ts
[warning] 57-57: src/screens/Users/Organization.mocks.ts#L57
Added line #L57 was not covered by tests
[warning] 68-68: src/screens/Users/Organization.mocks.ts#L68
Added line #L68 was not covered by tests
[warning] 77-77: src/screens/Users/Organization.mocks.ts#L77
Added line #L77 was not covered by tests
[warning] 236-236: src/screens/Users/Organization.mocks.ts#L236
Added line #L236 was not covered by tests
[warning] 243-243: src/screens/Users/Organization.mocks.ts#L243
Added line #L243 was not covered by tests
[warning] 284-284: src/screens/Users/Organization.mocks.ts#L284
Added line #L284 was not covered by tests
🔇 Additional comments (4)
src/screens/Users/Organization.mocks.ts (1)
84-101
: Use unique email addresses in mock dataAs previously mentioned, the email '[email protected]' is used for both John Doe and as the creator in multiple mock entries. This could lead to unrealistic test scenarios and may mask issues related to email uniqueness constraints.
Consider assigning unique email addresses for each mock user and creator to improve the reliability of your tests:
- email: '[email protected]', + email: '[email protected]',This adjustment helps ensure that your test data accurately reflects real-world scenarios.
src/screens/Users/User.mocks.ts (1)
119-119
: LGTM! Email update matches the user's first name.The change from '[email protected]' to '[email protected]' for the user with first name 'Jane' improves data consistency.
Also applies to: 354-354
src/screens/Users/Users.spec.tsx (2)
13-20
: LGTM! Clean import organization.The imports are well-organized, clearly separating the mock data imports from other dependencies.
733-781
: LGTM! Comprehensive test for empty search results.The test thoroughly verifies both the presence and content of the "No results found" message, including the search query in the message.
@syedali237 It looks like coderabbit approved, but its not showing in your checks. |
What kind of change does this PR introduce?
Testing
Issue Number:
Fixes #3036
If relevant, did you update the documentation?
No
Summary
Added test cases in src/screens/Users/Users.spec.tsx to increase code coverage in src/screens/Users/Users.tsx.
Moved mocks in the .mocks file, to ensure code readability.
Does this PR introduce a breaking change?
No
Checklist
CodeRabbit AI Review
Test Coverage
Other information
Have you read the contributing guide?
Summary by CodeRabbit
Tests
Refactor
Chores