Skip to content

test: add unit tests for GeneralCompliantComponent #2018

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

addresskrish
Copy link

Proposed change

Resolves #1835

Added comprehensive unit tests for GeneralCompliantComponent to improve coverage and ensure consistent behavior across different props and edge cases.

Changes include:

  • Rendering with minimal required props
  • Conditional styling for compliant=true and compliant=false
  • Rendering with provided title and custom icon
  • Accessibility checks for role/label
  • Edge case handling for empty title

Checklist

  • I've read and followed the contributing guidelines.
  • I've run make check-test locally; all checks and tests passed.

Copy link
Contributor

coderabbitai bot commented Aug 8, 2025

Summary by CodeRabbit

  • Tests

    • Added comprehensive unit tests for the status/compliance indicator component, covering rendering, styling based on state, tooltip display, accessibility roles/labels, and custom icon support.
  • Chores

    • Added a DOM testing utility to development dependencies to enhance component testing capabilities.

No user-facing features or behavior changes were introduced in this release.

Walkthrough

Added a new unit test file for GeneralCompliantComponent and updated frontend devDependencies to include @testing-library/dom.

Changes

Cohort / File(s) Change Summary
Unit tests
frontend/__tests__/unit/components/GeneralCompliantComponent.test.tsx
Added tests verifying rendering with minimal props, prop-driven styling (compliant true/false), custom icon rendering, empty-title edge case, tooltip/title presence, and accessibility role/label checks.
Dev dependency update
frontend/package.json
Added @testing-library/dom@^10.4.1 to devDependencies.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Assessment against linked issues

Objective Addressed Explanation
Renders successfully with minimal required props; Text/content rendering; DOM structure / classNames / styles (#1835)
Conditional rendering logic; Prop-based behavior; Default values and fallbacks (#1835)
Handles edge cases and invalid inputs (#1835)
Accessibility roles and labels (#1835)
Event handling; State changes / internal logic (#1835) Tests do not simulate user events or assert internal state transitions or callback invocations.

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Addition of @testing-library/dom to devDependencies (frontend/package.json) Not explicitly requested by the linked issue (which only required tests), though it's a supportive test utility; it's ancillary to the stated objectives.

Suggested reviewers

  • arkid15r

📜 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 b3d52a0 and 97ea30d.

📒 Files selected for processing (1)
  • frontend/package.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/package.json
✨ Finishing Touches
🧪 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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: 4

🧹 Nitpick comments (7)
frontend/package.json (1)

73-73: Avoid the extra dependency by re-exported utilities

You don't need a direct dependency on @testing-library/dom if you import screen from @testing-library/react. It re-exports DOM utilities. Simplify the tree and avoid version skew by removing this dep once imports are updated in the test.

-    "@testing-library/dom": "^10.4.1",
frontend/__tests__/unit/components/GeneralCompliantComponent.test.tsx (6)

9-13: Tighten test prop types; avoid any

Prefer the concrete icon type to catch mismatches at compile time.

+import type { IconDefinition } from '@fortawesome/fontawesome-svg-core';
@@
 type GeneralCompliantComponentProps = {
   compliant: boolean;
-  icon: any;
+  icon: IconDefinition;
   title: string;
 };

39-42: Minor duplication with the first render test

This largely overlaps “renders successfully with minimal required props.” Consider merging or making the assertion more specific (e.g., verify structure/order around icon + title).


44-48: Tooltip assertion is brittle without interaction

Asserting raw text risks false positives if the title is also visible inline. Prefer an accessible query (e.g., role="tooltip") and simulate hover if the tooltip is conditional.

Example approach:

  • If using a real tooltip: use user-event to hover the trigger, then assert by role.
  • If using title/aria-label: assert via getByTitle or toHaveAttribute.
-import { faCertificate } from '@fortawesome/free-solid-svg-icons';
+import { faCertificate } from '@fortawesome/free-solid-svg-icons';
+import userEvent from '@testing-library/user-event';
@@
-  it('renders tooltip with the title', () => {
-    const { getByText } = render(<GeneralCompliantComponent {...baseProps} title="Tooltip Title" />);
-    // Tooltip content is rendered, but may require hover simulation in real DOM
-    expect(getByText('Tooltip Title')).toBeInTheDocument();
-  });
+  it('shows tooltip content on hover', async () => {
+    render(<GeneralCompliantComponent {...baseProps} title="Tooltip Title" />);
+    const trigger = screen.getByText('Tooltip Title'); // Or a more specific trigger
+    await userEvent.hover(trigger);
+    expect(screen.getByRole('tooltip')).toHaveTextContent('Tooltip Title');
+  });

If the component does not render a role="tooltip", adapt to its actual a11y contract (e.g., getByTitle).


50-53: Empty title test is too weak

Asserting that container exists doesn't validate behavior. Check for expected fallback/absence instead (e.g., no visible title, aria-label fallback, or no crash with console error suppression if applicable).


64-68: Custom icon test should verify the override, not just presence of any SVG

Use a different icon and assert by a stable attribute (FontAwesome sets data-icon). This ensures the passed icon is actually used.

-import { faCertificate } from '@fortawesome/free-solid-svg-icons';
+import { faCertificate, faXmark } from '@fortawesome/free-solid-svg-icons';
@@
-  it('renders with custom icon', () => {
-    const customIcon = faCertificate; // Replace with another icon if needed
-    const { container } = render(<GeneralCompliantComponent {...baseProps} icon={customIcon} />);
-    expect(container.querySelector('svg')).toBeInTheDocument();
-  });
+  it('renders with custom icon', () => {
+    const customIcon = faXmark;
+    const { container } = render(<GeneralCompliantComponent {...baseProps} icon={customIcon} />);
+    expect(container.querySelector('svg[data-icon="xmark"]')).toBeInTheDocument();
+  });

If not using FontAwesome’s IconDefinition, assert with whatever stable selector the component renders.


4-4: Optional: move jest-dom setup to a global test setup

Importing jest-dom per test file is repetitive. Consider moving to a setup file (e.g., setupTests.ts) via Jest’s setupFilesAfterEnv.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1c1f1c2 and d1a3071.

📒 Files selected for processing (2)
  • frontend/__tests__/unit/components/GeneralCompliantComponent.test.tsx (1 hunks)
  • frontend/package.json (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 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#1714
File: frontend/src/components/ProjectTypeDashboardCard.tsx:8-12
Timestamp: 2025-07-08T17:07:50.988Z
Learning: In the OWASP/Nest project, union types for component props are not necessary when they would require creating separate type definitions. The project prefers inline prop type definitions even for props with specific string values, maintaining consistency with the single-use component prop pattern.
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: 2025-07-12T17:36:57.255Z
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/GeneralCompliantComponent.test.tsx

@addresskrish
Copy link
Author

Hi @arkid15r, I’ve finished the changes for this PR and all available checks have passed. Please review when you have time.

Copy link
Collaborator

@arkid15r arkid15r left a comment

Choose a reason for hiding this comment

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

@kasya
Copy link
Collaborator

kasya commented Aug 9, 2025

@addresskrish Do you plan to address requested changes?
Please check our contributing guide and update the PR. Or we'll have to assign this issue to someone else.

@addresskrish
Copy link
Author

Hi @kasya , yes, I'm working on the requested changes and will update the PR soon.

Comment on lines +70 to +73
// Add more tests as needed for event handling, state, etc.
});

// ...existing code...
Copy link
Collaborator

Choose a reason for hiding this comment

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

@addresskrish We totally support using AI for tests generation, but at least check what it generates and clean the code up before committing changes.
Also the tests fail right now in many cases. Please run make test-frontend-unit locally and address all issues

render(<GeneralCompliantComponent {...baseProps} />);
const iconElement = screen.getByText(baseProps.title); // Asserts the title text is visible
expect(iconElement).toBeInTheDocument();
// Or, if the icon has a specific role, you can check for that
Copy link
Collaborator

Choose a reason for hiding this comment

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

This also should be removed

Copy link
Collaborator

Choose a reason for hiding this comment

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

Revert this too - we don't need this new package

Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add tests for <GeneralCompliantComponent> component
3 participants