🧪 Add tests for useCardSettings hook#458
Conversation
Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
|
👋 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 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 reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
|
The latest updates on your projects. Learn more about Vercel for GitHub. 1 Skipped Deployment
|
|
Warning Review limit reached
Next review available in: 8 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
| 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: |
There was a problem hiding this comment.
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!
| 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 |
There was a problem hiding this comment.
normalizeCardLayout の変換後の値に依存している
このテストは DEFAULT_CARD_LAYOUT をそのまま localStorage に保存し、「値が同一なら参照が変わらない」ことを toBe(参照等価)で検証しています。しかし loadCardSettings は内部で normalizeCardLayout(parsedLayout) を呼ぶため、初期 useState で生成される参照は normalizeCardLayout の出力です。DEFAULT_CARD_LAYOUT が normalizeCardLayout の冪等入力でない場合、テストが突然失敗する可能性があります。
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.|
|
||
| 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(); | ||
| }); | ||
| }); |
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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.
| layout: customLayout as any, | |
| layout: customLayout, |
References
- Maintain explicit return types for functions in TypeScript to ensure type safety and API clarity.
| 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); | ||
| }); |
There was a problem hiding this comment.
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"); |
There was a problem hiding this comment.
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.
| const savedProfileBlock = savedLayout.blocks.find((b: any) => b.id === "profile"); | |
| const savedProfileBlock = savedLayout.blocks.find((b: { id: string; visible: boolean }) => b.id === "profile"); |
References
- 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>
🎯 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
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 は呼ばれない%%{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 は呼ばれないPrompt To Fix All With AI
Reviews (1): Last reviewed commit: "test: Add unit tests for useCardSettings..." | Re-trigger Greptile