Skip to content

🧪 Add tests for useCardSettings hook#458

Open
is0692vs wants to merge 2 commits into
mainfrom
test-use-card-settings-199190847730550437
Open

🧪 Add tests for useCardSettings hook#458
is0692vs wants to merge 2 commits into
mainfrom
test-use-card-settings-199190847730550437

Conversation

@is0692vs

@is0692vs is0692vs commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

🎯 What: Added missing tests for useCardSettings hook
📊 Coverage: Covered happy paths, storage integrations, and edge cases
Result: Increased test reliability and coverage for the hook.


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

Greptile Summary

useCardSettings フックの欠損テストを追加した PR です。ハッピーパス・localStorage との統合・ハイドレーションのエッジケース・非ハイドレート時の書き込み抑制など 8 ケースをカバーしています。

  • ハイドレーションの再実行防止テスト (should not hydrate if already hydrated)loadCardSettingsSpy を2回のレンダー後に設定しているため、検証対象のレンダーを実際に監視できておらず、早期リターンの動作を証明できていません。
  • 参照等価性テスト (toBe) が normalizeCardLayout の冪等性に依存しており、将来の実装変更で壊れやすい作りになっています。

Confidence Score: 3/5

テストのみの変更であり、プロダクションコードへの影響はありません。ただし「ハイドレーション再実行防止」を検証するテストが構造的に意図した挙動を証明できていないため、マージ前に修正が必要です。

「should not hydrate if already hydrated」テストにおいて loadCardSettingsSpy が2回のレンダー後に設定されており、早期リターンを証明すべき rerender を監視できていません。偽陽性となり、将来のリグレッションを検知できない状態です。

src/hooks/tests/useCardSettings.test.ts — 特に「should not hydrate if already hydrated」テストのスパイ設定ロジックを要確認

Important Files Changed

Filename Overview
src/hooks/tests/useCardSettings.test.ts useCardSettings フックの新規テストファイル。ハッピーパス・localStorage 統合・エッジケースを網羅しているが、「should not hydrate if already hydrated」テストでスパイの設定タイミングが遅く、検証対象のレンダーを実際には監視できていない構造的な問題がある。

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
    participant Test
    participant Hook as useCardSettings
    participant Storage as localStorage
    participant Lib as cardSettings lib

    Note over Test,Lib: mounted=false の初期レンダー
    Test->>Hook: "renderHook(mounted=false)"
    Hook->>Lib: loadCardSettings() [useState lazy init x2]
    Lib->>Storage: getItem(card-layout) / getItem(card-display-options)
    Storage-->>Lib: null or stored value
    Lib-->>Hook: layout, options
    Note over Hook: isHydrated=false 早期リターン

    Note over Test,Lib: mounted=true へ切り替え
    Test->>Hook: "rerender(mounted=true)"
    Hook->>Lib: loadCardSettings() [hydration effect]
    Lib-->>Hook: layout, options
    Hook->>Hook: setLayout / setDisplayOptions / setIsHydrated(true)
    Hook->>Lib: saveCardSettings(layout, options)
    Lib->>Storage: setItem x2

    Note over Test,Lib: 2回目以降の rerender
    Test->>Hook: "rerender(mounted=true)"
    Hook-->>Hook: "早期リターン(isHydrated=true)"
    Note over Hook: loadCardSettings は呼ばれない
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
    participant Test
    participant Hook as useCardSettings
    participant Storage as localStorage
    participant Lib as cardSettings lib

    Note over Test,Lib: mounted=false の初期レンダー
    Test->>Hook: "renderHook(mounted=false)"
    Hook->>Lib: loadCardSettings() [useState lazy init x2]
    Lib->>Storage: getItem(card-layout) / getItem(card-display-options)
    Storage-->>Lib: null or stored value
    Lib-->>Hook: layout, options
    Note over Hook: isHydrated=false 早期リターン

    Note over Test,Lib: mounted=true へ切り替え
    Test->>Hook: "rerender(mounted=true)"
    Hook->>Lib: loadCardSettings() [hydration effect]
    Lib-->>Hook: layout, options
    Hook->>Hook: setLayout / setDisplayOptions / setIsHydrated(true)
    Hook->>Lib: saveCardSettings(layout, options)
    Lib->>Storage: setItem x2

    Note over Test,Lib: 2回目以降の rerender
    Test->>Hook: "rerender(mounted=true)"
    Hook-->>Hook: "早期リターン(isHydrated=true)"
    Note over Hook: loadCardSettings は呼ばれない
Loading
Prompt To Fix All With AI
Fix the following 3 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 3
src/hooks/__tests__/useCardSettings.test.ts:71-93
**スパイの設定タイミングが遅すぎる**

`loadCardSettingsSpy` が2回目の `rerender` が完了した後(87行目)に設定されており、3回目の rerender の呼び出しのみを監視しています。2回目の rerender(85行目)で `loadCardSettings` が呼ばれたかどうかは一切検証されていないため、「既に hydrate済みの場合は早期リターンする」という動作を実際には証明できていません。スパイは `renderHook` よりも前に設定し、全 rerender 後のトータル呼び出し回数を検証するべきです。

### Issue 2 of 3
src/hooks/__tests__/useCardSettings.test.ts:39-57
**`normalizeCardLayout` の変換後の値に依存している**

このテストは `DEFAULT_CARD_LAYOUT` をそのまま `localStorage` に保存し、「値が同一なら参照が変わらない」ことを `toBe`(参照等価)で検証しています。しかし `loadCardSettings` は内部で `normalizeCardLayout(parsedLayout)` を呼ぶため、初期 `useState` で生成される参照は `normalizeCardLayout` の出力です。`DEFAULT_CARD_LAYOUT``normalizeCardLayout` の冪等入力でない場合、テストが突然失敗する可能性があります。

### Issue 3 of 3
src/hooks/__tests__/useCardSettings.test.ts:141-164
**`setItem` スパイを `renderHook` より前に設定することを推奨**

`Storage.prototype.setItem` へのスパイはテスト本体内・`renderHook` の後に設定されています。`renderHook` より前にスパイを設定することで、フック初期化時の副作用も含めてすべての `setItem` 呼び出しを監視でき、将来的な副作用の追加を見逃すリスクを下げられます。

Reviews (1): Last reviewed commit: "test: Add unit tests for useCardSettings..." | Re-trigger Greptile

Greptile also left 3 inline comments 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 10, 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 10, 2026 7:32am

@coderabbitai

coderabbitai Bot commented Jul 10, 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: 8 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: 6e59707f-22e6-4d96-a2df-0efb62738395

📥 Commits

Reviewing files that changed from the base of the PR and between 05bc250 and d0ad2ee.

📒 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 test-use-card-settings-199190847730550437

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.

@codecov

codecov Bot commented Jul 10, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Comment on lines +71 to +93
rerender({ mounted: true });

expect(result.current.displayOptions.showAvatar).toBe(false);
expect(result.current.layout).toEqual(customLayout);
});

it("should not hydrate if already hydrated", () => {
// Spy on setItem to see if saveCardSettings was called again
const saveCardSettingsSpy = vi.spyOn(cardSettingsLib, 'saveCardSettings');

const { rerender } = renderHook(({ mounted }) => useCardSettings(mounted), {
initialProps: { mounted: true }
});

// Initial mount hydration complete
expect(saveCardSettingsSpy).toHaveBeenCalledTimes(1);

// Rerender again with mounted: true
rerender({ mounted: true });

// It should not trigger hydration logic again, but saveCardSettings will trigger
// because of useEffect dependencies unless we verify state setter didn't fire again.
// Testing the early return in the first useEffect:

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.

P1 スパイの設定タイミングが遅すぎる

loadCardSettingsSpy が2回目の rerender が完了した後(87行目)に設定されており、3回目の rerender の呼び出しのみを監視しています。2回目の rerender(85行目)で loadCardSettings が呼ばれたかどうかは一切検証されていないため、「既に hydrate済みの場合は早期リターンする」という動作を実際には証明できていません。スパイは renderHook よりも前に設定し、全 rerender 後のトータル呼び出し回数を検証するべきです。

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

Comment:
**スパイの設定タイミングが遅すぎる**

`loadCardSettingsSpy` が2回目の `rerender` が完了した後(87行目)に設定されており、3回目の rerender の呼び出しのみを監視しています。2回目の rerender(85行目)で `loadCardSettings` が呼ばれたかどうかは一切検証されていないため、「既に hydrate済みの場合は早期リターンする」という動作を実際には証明できていません。スパイは `renderHook` よりも前に設定し、全 rerender 後のトータル呼び出し回数を検証するべきです。

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

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +39 to +57
window.localStorage.setItem("card-layout", JSON.stringify(DEFAULT_CARD_LAYOUT));

const { result, rerender } = renderHook(({ mounted }) => useCardSettings(mounted), {
initialProps: { mounted: false }
});

const initialLayout = result.current.layout;
const initialOptions = result.current.displayOptions;

// Rerender as mounted
rerender({ mounted: true });

// Ensure state references didn't change because values were identical
expect(result.current.layout).toBe(initialLayout);
expect(result.current.displayOptions).toBe(initialOptions);
});

it("should hydrate when mounted becomes true and change state if options differ", () => {
// Change options so they differ from initial state to hit true branch of ternary

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 normalizeCardLayout の変換後の値に依存している

このテストは DEFAULT_CARD_LAYOUT をそのまま localStorage に保存し、「値が同一なら参照が変わらない」ことを toBe(参照等価)で検証しています。しかし loadCardSettings は内部で normalizeCardLayout(parsedLayout) を呼ぶため、初期 useState で生成される参照は normalizeCardLayout の出力です。DEFAULT_CARD_LAYOUTnormalizeCardLayout の冪等入力でない場合、テストが突然失敗する可能性があります。

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

Comment:
**`normalizeCardLayout` の変換後の値に依存している**

このテストは `DEFAULT_CARD_LAYOUT` をそのまま `localStorage` に保存し、「値が同一なら参照が変わらない」ことを `toBe`(参照等価)で検証しています。しかし `loadCardSettings` は内部で `normalizeCardLayout(parsedLayout)` を呼ぶため、初期 `useState` で生成される参照は `normalizeCardLayout` の出力です。`DEFAULT_CARD_LAYOUT``normalizeCardLayout` の冪等入力でない場合、テストが突然失敗する可能性があります。

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

Comment on lines +141 to +164

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

expect(result.current.isBlockVisible("profile")).toBe(false);
// @ts-expect-error Testing invalid id
expect(result.current.isBlockVisible("invalid-id")).toBe(false);
});

it("should not save settings to localStorage if not hydrated", () => {
// Spy on setItem
const setItemSpy = vi.spyOn(Storage.prototype, 'setItem');

const { result } = renderHook(() => useCardSettings(false));

act(() => {
result.current.toggleDisplayOption("showAvatar");
});

// It shouldn't have setItem because it's not mounted and hydrated
expect(setItemSpy).not.toHaveBeenCalled();
});
});

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 setItem スパイを renderHook より前に設定することを推奨

Storage.prototype.setItem へのスパイはテスト本体内・renderHook の後に設定されています。renderHook より前にスパイを設定することで、フック初期化時の副作用も含めてすべての setItem 呼び出しを監視でき、将来的な副作用の追加を見逃すリスクを下げられます。

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

Comment:
**`setItem` スパイを `renderHook` より前に設定することを推奨**

`Storage.prototype.setItem` へのスパイはテスト本体内・`renderHook` の後に設定されています。`renderHook` より前にスパイを設定することで、フック初期化時の副作用も含めてすべての `setItem` 呼び出しを監視でき、将来的な副作用の追加を見逃すリスクを下げられます。

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

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@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, covering initialization, hydration logic, and state updates. The review identified opportunities to improve type safety by removing unnecessary any type assertions and suggested simplifying the hydration test case for better clarity and focus.

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.


// Mock loadCardSettings to return new values during effect execution
vi.spyOn(cardSettingsLib, 'loadCardSettings').mockReturnValueOnce({
layout: customLayout as any,

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 as any type assertion here compromises type safety and appears to be unnecessary as the customLayout object seems to conform to the CardLayout type. Please remove the as any cast. If this causes a type error, it should be resolved by explicitly typing the customLayout variable rather than bypassing the type system.

Suggested change
layout: customLayout as any,
layout: customLayout,
References
  1. Maintain explicit return types for functions in TypeScript to ensure type safety and API clarity.

Comment on lines +77 to +99
it("should not hydrate if already hydrated", () => {
// Spy on setItem to see if saveCardSettings was called again
const saveCardSettingsSpy = vi.spyOn(cardSettingsLib, 'saveCardSettings');

const { rerender } = renderHook(({ mounted }) => useCardSettings(mounted), {
initialProps: { mounted: true }
});

// Initial mount hydration complete
expect(saveCardSettingsSpy).toHaveBeenCalledTimes(1);

// Rerender again with mounted: true
rerender({ mounted: true });

// It should not trigger hydration logic again, but saveCardSettings will trigger
// because of useEffect dependencies unless we verify state setter didn't fire again.
// Testing the early return in the first useEffect:
const loadCardSettingsSpy = vi.spyOn(cardSettingsLib, 'loadCardSettings');
rerender({ mounted: true });

// The load shouldn't be called again since isHydrated is true
expect(loadCardSettingsSpy).toHaveBeenCalledTimes(0);
});

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

This test case is a bit complex and mixes the concerns of persistence (saveCardSettings) and hydration (loadCardSettings). It can be simplified to more clearly focus on its stated goal: ensuring hydration doesn't happen more than once.

it("should not re-hydrate if already hydrated", () => {
  const { rerender } = renderHook(() => useCardSettings(true));
  const loadCardSettingsSpy = vi.spyOn(cardSettingsLib, 'loadCardSettings');
  rerender();
  expect(loadCardSettingsSpy).not.toHaveBeenCalled();
});


// Verify it was saved to storage
const savedLayout = JSON.parse(window.localStorage.getItem("card-layout") || "{}");
const savedProfileBlock = savedLayout.blocks.find((b: any) => b.id === "profile");

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

To improve type safety, you can provide a more specific type for the b parameter instead of any. Since you're accessing the id and visible properties, you can type it as an object containing those properties.

Suggested change
const savedProfileBlock = savedLayout.blocks.find((b: any) => b.id === "profile");
const savedProfileBlock = savedLayout.blocks.find((b: { id: string; visible: boolean }) => b.id === "profile");
References
  1. Maintain explicit return types for functions in TypeScript to ensure type safety and API clarity.

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
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