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

test(web): add component test of accessibility page #1349

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

Conversation

caichi-t
Copy link
Contributor

@caichi-t caichi-t commented Jan 15, 2025

Overview

This PR adds the test for component test of accessibility page.
I refactored and optimized components to run the test.

Memo

E2E test has been passed.

Summary by CodeRabbit

  • Tests

    • Added comprehensive test suite for the Accessibility component.
    • Validated rendering, toggle functionality, scope limitations, and user rights impact.
  • Refactor

    • Updated component structure and data types.
    • Simplified form handling and state management.
    • Enhanced error handling in update processes.
  • Chores

    • Improved testing setup with custom implementations for browser APIs.

@caichi-t caichi-t requested a review from nourbalaha as a code owner January 15, 2025 06:52
Copy link
Contributor

coderabbitai bot commented Jan 15, 2025

Walkthrough

This pull request introduces comprehensive changes to the Accessibility component across multiple files. The modifications focus on refactoring the component's state management, testing, and functionality. The changes include updating type definitions, restructuring the component's logic, adding a detailed test suite, and improving the testing setup. The primary goal appears to be enhancing the component's robustness, testability, and flexibility in handling model accessibility settings.

Changes

File Change Summary
web/src/components/molecules/Accessibility/index.test.tsx Added comprehensive Vitest test suite for Accessibility component, covering rendering, toggle functionality, scope limitations, and user rights.
web/src/components/molecules/Accessibility/index.tsx Significant type and implementation changes, including updated ModelDataType, modified Props, new state management, and improved form handling.
web/src/components/organisms/Project/Accessibility/hooks.ts Removed form handling logic, simplified handlePublicUpdate function, and updated parameter handling.
web/src/components/organisms/Project/Accessibility/index.tsx Updated component to work with new hook structure and removed deprecated properties.
web/src/test/setup.ts Added beforeAll hook, implemented window.getComputedStyle and matchMedia for improved testing environment.

Sequence Diagram

sequenceDiagram
    participant User
    participant AccessibilityComponent
    participant AccessibilityHook
    participant API

    User->>AccessibilityComponent: Interact with settings
    AccessibilityComponent->>AccessibilityHook: Request update
    AccessibilityHook->>API: Send update request
    API-->>AccessibilityHook: Return update result
    AccessibilityHook-->>AccessibilityComponent: Update component state
    AccessibilityComponent->>User: Reflect changes
Loading

Possibly related PRs

Suggested reviewers

  • nourbalaha

Poem

🐰 A Rabbit's Ode to Accessibility 🔧

In lines of code, we dance and weave,
Testing components that we believe
Switches toggle, buttons gleam bright
Accessibility takes its flight!

Hop hop hooray! 🎉


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f3c2cd1 and 7731dd5.

📒 Files selected for processing (1)
  • web/src/components/molecules/Accessibility/index.test.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • web/src/components/molecules/Accessibility/index.test.tsx
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: ci-web / ci
  • GitHub Check: Redirect rules - reearth-cms
  • GitHub Check: Header rules - reearth-cms
  • GitHub Check: Pages changed - reearth-cms

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?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

@github-actions github-actions bot added the web label Jan 15, 2025
Copy link

netlify bot commented Jan 15, 2025

Deploy Preview for reearth-cms ready!

Name Link
🔨 Latest commit 88ba4b5
🔍 Latest deploy log https://app.netlify.com/sites/reearth-cms/deploys/67a2de1339050000085b0024
😎 Deploy Preview https://deploy-preview-1349--reearth-cms.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

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: 3

🔭 Outside diff range comments (1)
web/src/components/molecules/Accessibility/index.tsx (1)

Line range hint 186-196: Enhance accessibility for token visibility toggle.

The token visibility toggle button lacks proper accessibility attributes for screen readers.

Add ARIA attributes to improve accessibility:

 <Icon
   icon={visible ? "eye" : "eyeInvisible"}
+  aria-label={visible ? t("Hide token") : t("Show token")}
+  role="button"
+  tabIndex={0}
   onClick={() => {
     setVisible(prev => !prev);
   }}
+  onKeyPress={(e) => {
+    if (e.key === 'Enter' || e.key === ' ') {
+      setVisible(prev => !prev);
+    }
+  }}
 />
🧹 Nitpick comments (4)
web/src/test/setup.ts (1)

20-25: Enhance matchMedia mock implementation.

The current matchMedia mock is incomplete. Modern web standards require additional methods and properties.

Consider enhancing the mock with additional required properties:

 Object.defineProperty(window, "matchMedia", {
   value: () => ({
+    matches: false,
+    media: "",
     addListener: () => {},
     removeListener: () => {},
+    addEventListener: () => {},
+    removeEventListener: () => {},
+    dispatchEvent: () => false,
   }),
 });
web/src/components/organisms/Project/Accessibility/hooks.ts (1)

134-148: Enhance error logging for token regeneration.

While the error handling is good, the error logging could be more informative.

Consider enhancing the error logging:

     } catch (e) {
-      console.error(e);
+      console.error("Failed to regenerate public API token:", e);
       Notification.error({
         message: t("The attempt to re-generate the Public API Token has failed."),
       });
web/src/components/molecules/Accessibility/index.test.tsx (1)

7-175: Add tests for error scenarios and loading states.

The test suite is well-structured and comprehensive for happy paths, but could benefit from additional coverage.

Consider adding tests for:

  1. Error handling when public update fails
  2. Error handling when token regeneration fails
  3. Component behavior during loading states
  4. Accessibility attributes (aria-labels, roles)

Example test structure:

test("Should show error notification when update fails", async () => {
  const failingUpdate = () => Promise.reject(new Error("Update failed"));
  render(
    <Accessibility
      {...defaultProps}
      onPublicUpdate={failingUpdate}
    />
  );
  // Test implementation
});

test("Should disable interactions during loading state", async () => {
  render(
    <Accessibility
      {...defaultProps}
      updateLoading={true}
    />
  );
  // Test implementation
});
web/src/components/molecules/Accessibility/index.tsx (1)

60-83: Well-implemented change tracking logic!

The use of useRef for changedModels and useCallback for handleValuesChange is an efficient approach to track form changes. The implementation correctly prevents unnecessary re-renders.

Consider memoizing the equality check condition to improve readability:

+const isFormUnchanged = useCallback(
+  (values: FormType) =>
+    initialValues.scope === values.scope &&
+    initialValues.assetPublic === values.assetPublic &&
+    changedModels.current.size === 0,
+  [initialValues]
+);

 const handleValuesChange = useCallback(
   (changedValues: Partial<FormType>, values: FormType) => {
     if (changedValues?.models) {
       const modelId = Object.keys(changedValues.models)[0];
       if (changedModels.current.has(modelId)) {
         changedModels.current.delete(modelId);
       } else {
         changedModels.current.set(modelId, changedValues.models[modelId]);
       }
     }
-    if (
-      initialValues.scope === values.scope &&
-      initialValues.assetPublic === values.assetPublic &&
-      changedModels.current.size === 0
-    ) {
+    if (isFormUnchanged(values)) {
       setIsSaveDisabled(true);
     } else {
       setIsSaveDisabled(false);
     }
   },
-  [initialValues],
+  [isFormUnchanged],
 );
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c0a9ef2 and f3c2cd1.

📒 Files selected for processing (5)
  • web/src/components/molecules/Accessibility/index.test.tsx (1 hunks)
  • web/src/components/molecules/Accessibility/index.tsx (5 hunks)
  • web/src/components/organisms/Project/Accessibility/hooks.ts (5 hunks)
  • web/src/components/organisms/Project/Accessibility/index.tsx (1 hunks)
  • web/src/test/setup.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: ci-web / ci
  • GitHub Check: Redirect rules - reearth-cms
  • GitHub Check: Header rules - reearth-cms
  • GitHub Check: Pages changed - reearth-cms
🔇 Additional comments (3)
web/src/components/organisms/Project/Accessibility/index.tsx (1)

7-30: LGTM! Clean refactoring of component props.

The refactoring improves component maintainability by:

  • Removing form instance dependency in favor of direct value management
  • Simplifying prop interface with AccessibilityMolecule
web/src/test/setup.ts (1)

27-30: LGTM! Proper preservation of getComputedStyle functionality.

The implementation correctly preserves the original getComputedStyle behavior while allowing test overrides.

web/src/components/molecules/Accessibility/index.tsx (1)

21-23: Consider security implications of exposing API endpoints.

The endpoint field in ModelDataType exposes API URLs in the UI. While this improves developer experience, ensure that these endpoints don't expose sensitive information or internal infrastructure details.

✅ Verification successful

Endpoint exposure is secure and follows best practices

The exposure of API endpoints is an intentional design choice that follows security best practices:

  • Endpoints only expose validated model keys (alphanumeric + _-)
  • Access is protected by scope controls and token authentication
  • No sensitive information is exposed in the URLs
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential sensitive information in API endpoints
rg -i "(internal|private|secret|password|key|token|credential)" --type ts

Length of output: 87675

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

Successfully merging this pull request may close these issues.

1 participant