Skip to content

Conversation

@Dhirajsharma2060
Copy link
Contributor

Created tests for task issue #1915

This PR introduces a complete unit test suite for the <SortBy /> component to ensure it behaves correctly under various scenarios. The tests focus on rendering validation, prop-driven behavior, user interactions, accessibility, and UI logic.


Summary of Changes

  • ✅ Rendered component with minimal props
  • 🧪 Verified conditional rendering of ascending/descending sort icons based on selectedOrder
  • 🎯 Validated selected value display based on selectedSortOption
  • 🔁 Simulated user interactions for:
    • Changing the selected sort option (onSortChange)
    • Toggling sort direction (onOrderChange)
  • ♿ Ensured accessibility roles (label, select, img) are correctly applied
  • 📦 Isolated tests using afterEach with jest.clearAllMocks

Checklist

Checklist Item Status Test Reference
Renders successfully with minimal required props renders successfully with minimal required props
Conditional rendering logic renders ascending/descending icon based on selectedOrder
Prop-based behavior – different props affect output renders all options and selects the correct one, other prop-driven tests
Event handling – simulate user actions and verify callbacks calls onSortChange, toggles order when the button is clicked
State changes / internal logic (Component is stateless – props drive behavior)
Default values and fallbacks Verified via initial selected value and order
Text and content rendering Label and selected option rendering tested
Accessibility roles and labels uses proper accessibility attributes
DOM structure / classNames / styles Icon class presence (e.g., fa-arrow-up-wide-short) tested

Developer Notes

  • I've read and followed the contributing guidelines.
  • I've run make check-test locally; all checks and tests passed.
  • Followed structure based on AutoScrollToTop.test.tsx for consistency
  • Used @testing-library/react and act() for rendering and async interactions
  • Referenced best practices from existing tests in the components/__tests__ folder

✅ The <SortBy /> component tests passed successfully when run directly using:

pnpm test:unit __tests__/unit/components/SortBy.test.tsx

⚠️ While running make test-frontend-unit, some unrelated test files failed due to global Jest coverage thresholds (0%) not being met. These are not related to the current PR, and <SortBy /> remains fully tested and functional in isolation.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 3, 2025

Summary by CodeRabbit

  • Tests
    • Added a comprehensive test suite for the SortBy component, covering rendering, option selection, sort order toggling, callback invocation, and accessibility attributes.

Walkthrough

A new unit test suite for the SortBy React component has been added. The tests verify rendering, behavior, and accessibility, including option selection, sort order toggling, callback invocation, and accessibility attributes using React Testing Library and Jest.

Changes

Cohort / File(s) Change Summary
SortBy Component Unit Tests
frontend/__tests__/unit/components/SortBy.test.tsx
Added a comprehensive unit test suite for the SortBy React component, covering rendering, behavior, and accessibility.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Possibly related issues

Suggested reviewers

  • arkid15r
  • kasya

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a247251 and c1de740.

📒 Files selected for processing (1)
  • frontend/__tests__/unit/components/SortBy.test.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/tests/unit/components/SortBy.test.tsx
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

🧹 Nitpick comments (3)
frontend/__tests__/unit/components/SortBy.test.tsx (3)

30-40: Reasonable approach for testing component library elements.

The test correctly handles the limitation of testing dropdown options in component libraries. The use of data-slot="value" selector suggests this is a NextUI Select component, and the approach is appropriate for such libraries.

Consider verifying that all sort options are available by checking if they can be found when the dropdown is opened, if the component library supports it:

+ // Optionally test that options are available when dropdown opens
+ const select = screen.getByLabelText('Sort By :')
+ fireEvent.click(select)
+ expect(screen.getByText('Date')).toBeInTheDocument()

70-80: Consider more robust button selection.

The test correctly verifies the order toggle functionality, but relying on button index (buttons[1]) could be brittle if the component structure changes.

Consider using a more specific selector for the sort order button:

- // Get the second button (the sort order button)
- const buttons = screen.getAllByRole('button')
- fireEvent.click(buttons[1]) // The sort order button is the second button
+ // Get the sort order button by its icon or aria-label
+ const sortOrderButton = screen.getByRole('button', { name: /sort order/i }) 
+ // or find by the icon class if no aria-label exists
+ fireEvent.click(sortOrderButton)

82-94: Enhance accessibility testing specificity.

The test covers basic accessibility verification but could be more comprehensive in testing specific accessibility attributes.

Consider testing additional accessibility attributes:

  it('uses proper accessibility attributes', async () => {
    await act(async () => {
      render(<SortBy {...defaultProps} />)
    })
    const select = screen.getByLabelText('Sort By :')
    expect(select.tagName).toBe('SELECT')
+   expect(select).toHaveAttribute('aria-label', 'Sort By :')
    
-   // Use getAllByText to handle multiple elements with same text
-   const containers = screen.getAllByText('Sort By :')
-   const container = containers[0].closest('div')
-   expect(container).toBeInTheDocument()
+   // Test for proper labeling relationship
+   const label = screen.getByText('Sort By :')
+   expect(label.tagName).toBe('LABEL')
  })
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9642aa5 and a247251.

📒 Files selected for processing (1)
  • frontend/__tests__/unit/components/SortBy.test.tsx (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: Rajgupta36
PR: OWASP/Nest#1717
File: frontend/__tests__/unit/pages/createProgram.test.tsx:70-86
Timestamp: 2025-07-12T17:36:57.255Z
Learning: When testing React page components that use mocked form components, validation logic should be tested at the form component level, not the page level. Page-level tests should focus on authentication, role checking, submission handling, and navigation logic.
Learnt from: ahmedxgouda
PR: OWASP/Nest#1718
File: frontend/src/app/projects/dashboard/metrics/page.tsx:96-96
Timestamp: 2025-07-09T08:37:10.241Z
Learning: In the OWASP Nest project's MetricsPage component (frontend/src/app/projects/dashboard/metrics/page.tsx), the sorting dropdown intentionally uses selectionMode="multiple" to allow users to select multiple sorting criteria simultaneously. This enables complex sorting scenarios where users can sort by multiple fields in sequence.
Learnt from: codic-yeeshu
PR: OWASP/Nest#1444
File: frontend/src/components/NavDropDown.tsx:0-0
Timestamp: 2025-04-30T13:41:20.846Z
Learning: Use React's useId() hook rather than manually generating random strings when creating accessibility identifiers for UI components. This creates stable, unique IDs without causing hydration mismatches.
📚 Learning: when testing react page components that use mocked form components, validation logic should be teste...
Learnt from: Rajgupta36
PR: OWASP/Nest#1717
File: frontend/__tests__/unit/pages/createProgram.test.tsx:70-86
Timestamp: 2025-07-12T17:36:57.255Z
Learning: When testing React page components that use mocked form components, validation logic should be tested at the form component level, not the page level. Page-level tests should focus on authentication, role checking, submission handling, and navigation logic.

Applied to files:

  • frontend/__tests__/unit/components/SortBy.test.tsx
📚 Learning: in the owasp nest project's metricspage component (frontend/src/app/projects/dashboard/metrics/page....
Learnt from: ahmedxgouda
PR: OWASP/Nest#1718
File: frontend/src/app/projects/dashboard/metrics/page.tsx:96-96
Timestamp: 2025-07-09T08:37:10.241Z
Learning: In the OWASP Nest project's MetricsPage component (frontend/src/app/projects/dashboard/metrics/page.tsx), the sorting dropdown intentionally uses selectionMode="multiple" to allow users to select multiple sorting criteria simultaneously. This enables complex sorting scenarios where users can sort by multiple fields in sequence.

Applied to files:

  • frontend/__tests__/unit/components/SortBy.test.tsx
🔇 Additional comments (5)
frontend/__tests__/unit/components/SortBy.test.tsx (5)

1-3: LGTM!

The imports are appropriate for React component testing with the correct utilities from React Testing Library and the act helper from React.


5-19: LGTM!

The test setup is well-structured with comprehensive default props and proper mock cleanup. The use of jest.clearAllMocks() in afterEach ensures test isolation.


21-28: LGTM!

The test properly verifies basic rendering and uses accessibility-friendly queries with getByLabelText. The async/await pattern with act() is correctly implemented.


42-50: LGTM!

The test properly simulates user interaction and verifies the callback behavior. The use of act() around both rendering and the event ensures proper React state handling.


52-68: LGTM!

Both icon tests properly verify conditional rendering based on the selectedOrder prop. The use of getByRole('img', { hidden: true }) is correct for Font Awesome icons, and testing the CSS classes is an appropriate approach for verifying icon states.

@sonarqubecloud
Copy link

sonarqubecloud bot commented Aug 3, 2025

Copy link
Collaborator

@kasya kasya left a comment

Choose a reason for hiding this comment

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

These are good! Thank you @Dhirajsharma2060!

@kasya kasya enabled auto-merge August 3, 2025 17:04
@kasya kasya added this pull request to the merge queue Aug 3, 2025
Merged via the queue into OWASP:main with commit ba126d5 Aug 3, 2025
24 checks passed
@arkid15r arkid15r linked an issue Aug 4, 2025 that may be closed by this pull request
10 tasks
@arkid15r arkid15r mentioned this pull request Aug 4, 2025
10 tasks
trucodd pushed a commit to trucodd/Nest that referenced this pull request Aug 5, 2025
* test: add unit tests for SortBy component

* test: update SortBy component tests for prop naming and accessibility

* test: import React in SortBy component tests for consistency

* made some chnages

* test: update SortBy component tests for improved accessibility and clarity

* test: ensure order toggle button functionality in SortBy component tests

---------

Co-authored-by: Kate Golovanova <[email protected]>
@Dhirajsharma2060
Copy link
Contributor Author

Dhirajsharma2060 commented Nov 10, 2025

@arkid15r @kasya please add the labels on the PR as the program manager has asked to add the labels as per the contribution it was it was level 2 of gssoc25 because of this i am not in the leadersboard as well as certificate is also not generating so please

@arkid15r arkid15r added gssoc2025 GirlScript Summer of Code 2025 level 2 5 points labels Nov 10, 2025
@coderabbitai coderabbitai bot mentioned this pull request Nov 26, 2025
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

frontend frontend-tests gssoc2025 GirlScript Summer of Code 2025 level 2 5 points

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add tests for <SortBy> component

3 participants