Skip to content

🧪 Add tests for useCardSettings hook#468

Closed
is0692vs wants to merge 2 commits into
mainfrom
add-tests-use-card-settings-11644537351646032768
Closed

🧪 Add tests for useCardSettings hook#468
is0692vs wants to merge 2 commits into
mainfrom
add-tests-use-card-settings-11644537351646032768

Conversation

@is0692vs

@is0692vs is0692vs commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

🎯 What: The testing gap addressed is the lack of unit tests for the useCardSettings hook, which is responsible for state and localStorage synchronization of card configurations.
📊 Coverage: Scenarios covered include hook initialization, delayed hydration behavior (avoiding hydration when not mounted), update logic triggered upon mounting, saving configurations to storage, layout structure updates via toggleMainBlockVisibility, layout options updates via toggleDisplayOption, and checking block visibility.
Result: Test coverage for this custom hook has been introduced, significantly improving codebase reliability and confirming expected syncing behaviors with localStorage.


PR created automatically by Jules for task 11644537351646032768 started by @is0692vs

Greptile Summary

このPRは useCardSettings hook のテストを追加します。主な変更は以下です。

  • hook の初期化と mounted 後の hydration の検証。
  • localStorage 保存につながる表示オプション更新の検証。
  • レイアウト block の表示切り替えと visibility 判定の検証。

Confidence Score: 5/5

このPRは小さなテスト改善後に安全にマージできそうです。

  • 本番コードの変更はありません。
  • 追加テストの import と test 環境は既存設定に合っています。
  • レイアウト切り替えのテストは、実際の戻り値形状に近づけると回帰検出力が上がります。

src/hooks/tests/useCardSettings.test.ts

Important Files Changed

Filename Overview
src/hooks/tests/useCardSettings.test.ts useCardSettings の主要フローをカバーする新規テストで、レイアウト切り替えのモックだけ実装形状とずれています。
Prompt To Fix All With AI
Fix the following 1 code review issue. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 1
src/hooks/__tests__/useCardSettings.test.ts:63-65
**Mocked Layout Shape Diverges**

このモックは実際の `toggleBlockVisibility` と違い、`blocks[].visible` を更新せずにトップレベルの `toggled` だけを追加します。そのため `toggleMainBlockVisibility("stats")` のテストは、実際の `CardLayout` 更新が壊れても通ってしまい、hook とレイアウト更新処理の連携回帰を検出できません。

Reviews (1): Last reviewed commit: "test: add tests for useCardSettings hook" | Re-trigger Greptile

Greptile also left 1 inline comment on this PR.

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@vercel

vercel Bot commented Jul 17, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
github-user-summary Ignored Ignored Jul 17, 2026 6:57am

@coderabbitai

coderabbitai Bot commented Jul 17, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@is0692vs, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 36 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 76ce4efa-e9f5-43fa-bfd0-35adfb36ee40

📥 Commits

Reviewing files that changed from the base of the PR and between 0a9a1e0 and 6a085e7.

📒 Files selected for processing (2)
  • src/hooks/__tests__/useCardSettings.test.ts
  • src/hooks/useCardSettings.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch add-tests-use-card-settings-11644537351646032768

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

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

Comment on lines +63 to +65
(cardLayoutLib.toggleBlockVisibility as any).mockImplementation(
(prev: any, id: any) => ({ ...prev, toggled: id })
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Mocked Layout Shape Diverges

このモックは実際の toggleBlockVisibility と違い、blocks[].visible を更新せずにトップレベルの toggled だけを追加します。そのため toggleMainBlockVisibility("stats") のテストは、実際の CardLayout 更新が壊れても通ってしまい、hook とレイアウト更新処理の連携回帰を検出できません。

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/hooks/__tests__/useCardSettings.test.ts
Line: 63-65

Comment:
**Mocked Layout Shape Diverges**

このモックは実際の `toggleBlockVisibility` と違い、`blocks[].visible` を更新せずにトップレベルの `toggled` だけを追加します。そのため `toggleMainBlockVisibility("stats")` のテストは、実際の `CardLayout` 更新が壊れても通ってしまい、hook とレイアウト更新処理の連携回帰を検出できません。

How can I resolve this? If you propose a fix, please make it concise.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a comprehensive test suite for the useCardSettings hook. The review feedback focuses on improving test robustness and type safety. Key recommendations include removing unnecessary mocks of pure utility functions to assert on actual state changes, avoiding unsafe as any type assertions by using proper TypeScript types and Vitest's vi.mocked() utility, and correcting structural mismatches in the mock layout data.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

import { describe, it, expect, vi, beforeEach } from "vitest";
import { useCardSettings } from "../useCardSettings";
import * as cardSettingsLib from "@/lib/cardSettings";
import * as cardLayoutLib from "@/lib/cardLayout";

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Since we are removing the mock for @/lib/cardLayout and using the actual state changes in our assertions, the import of cardLayoutLib is no longer needed. Let's remove it.

import * as cardSettingsLib from "@/lib/cardSettings";
import * as cardLayoutLib from "@/lib/cardLayout";
import { DEFAULT_CARD_LAYOUT } from "@/lib/types";
import type { CardLayout } from "@/lib/types";

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Import CardBlockId from @/lib/types so we can use it for type casting in our tests instead of as any.

Suggested change
import type { CardLayout } from "@/lib/types";
import type { CardLayout, CardBlockId } from "@/lib/types";
References
  1. Maintain explicit return types for functions in TypeScript to ensure type safety and API clarity. If a type is only used for annotations, use 'import type' instead of removing the annotation to satisfy linting rules.

Comment on lines +19 to +25
vi.mock("@/lib/cardLayout", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/cardLayout")>();
return {
...actual,
toggleBlockVisibility: vi.fn(),
};
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Mocking pure utility functions like toggleBlockVisibility from @/lib/cardLayout is an anti-pattern that introduces unnecessary complexity and type-safety workarounds (such as as any casting). Since toggleBlockVisibility is a pure function, we can use its actual implementation directly in the tests.

Let's remove this mock entirely.

Comment on lines +46 to +53
const mockLoadedSettings = {
layout: {
...DEFAULT_CARD_LAYOUT,
blocks: [
{ id: "profile", visible: true, order: 0 },
{ id: "stats", visible: false, order: 1 },
]
} as CardLayout,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The mock layout uses an incorrect property order instead of column, which is the actual property defined in the CardBlock type. Using the type assertion as CardLayout masks this type mismatch.

Let's update the mock layout to adhere to the actual CardBlock type structure by using column and removing the unsafe type assertion.

  const mockLoadedSettings = {
    layout: {
      ...DEFAULT_CARD_LAYOUT,
      blocks: [
        { id: "profile", visible: true, column: "full" },
        { id: "stats", visible: false, column: "left" },
      ]
    },


beforeEach(() => {
vi.clearAllMocks();
(cardSettingsLib.loadCardSettings as any).mockReturnValue(mockLoadedSettings);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Avoid using as any type assertions when mocking functions. Instead, use Vitest's idiomatic vi.mocked() utility to maintain type safety.

Suggested change
(cardSettingsLib.loadCardSettings as any).mockReturnValue(mockLoadedSettings);
vi.mocked(cardSettingsLib.loadCardSettings).mockReturnValue(mockLoadedSettings);

Comment on lines +63 to +65
(cardLayoutLib.toggleBlockVisibility as any).mockImplementation(
(prev: any, id: any) => ({ ...prev, toggled: id })
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Since we are removing the mock for @/lib/cardLayout, we should also remove the mock implementation of toggleBlockVisibility here.

Comment on lines +113 to +125
it("toggleMainBlockVisibility should update layout using toggleBlockVisibility", () => {
const { result } = renderHook(() => useCardSettings(true));

act(() => {
result.current.toggleMainBlockVisibility("stats");
});

expect(cardLayoutLib.toggleBlockVisibility).toHaveBeenCalledWith(
mockLoadedSettings.layout,
"stats"
);
expect(result.current.layout).toHaveProperty("toggled", "stats");
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

With the mock of toggleBlockVisibility removed, we can assert on the actual state change of the layout blocks. This makes the test much more robust and type-safe.

  it("toggleMainBlockVisibility should update layout using toggleBlockVisibility", () => {
    const { result } = renderHook(() => useCardSettings(true));

    act(() => {
      result.current.toggleMainBlockVisibility("stats");
    });

    const statsBlock = result.current.layout.blocks.find((b) => b.id === "stats");
    expect(statsBlock?.visible).toBe(true);
  });


expect(result.current.isBlockVisible("profile")).toBe(true);
expect(result.current.isBlockVisible("stats")).toBe(false);
expect(result.current.isBlockVisible("non-existent-block" as any)).toBe(false);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Instead of using as any to pass an invalid block ID, use as CardBlockId to maintain better type safety while testing the fallback behavior.

Suggested change
expect(result.current.isBlockVisible("non-existent-block" as any)).toBe(false);
expect(result.current.isBlockVisible("non-existent-block" as CardBlockId)).toBe(false);

@codecov

codecov Bot commented Jul 17, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@is0692vs

Copy link
Copy Markdown
Contributor Author

Closing because this Jules-managed branch cannot maintain a stable review-loop head: after the target branch is incorporated or a review fix is pushed, the bot appends the original generated change again. The current head is therefore not reliably the commit that passed target-fresh CI and review.

@is0692vs is0692vs closed this Jul 18, 2026
@is0692vs
is0692vs deleted the add-tests-use-card-settings-11644537351646032768 branch July 18, 2026 09:15
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