Skip to content

🧪 [Add tests for useThemeColor hook]#108

Merged
is0692vs merged 3 commits intomainfrom
testing/use-theme-color-8717967491783105506
Mar 29, 2026
Merged

🧪 [Add tests for useThemeColor hook]#108
is0692vs merged 3 commits intomainfrom
testing/use-theme-color-8717967491783105506

Conversation

@is0692vs
Copy link
Copy Markdown
Contributor

🎯 What:
The useThemeColor React hook, which is responsible for asynchronously extracting dominant colors from user avatars and dynamically generating theme colors, previously lacked test coverage.

📊 Coverage:
The newly added test suite (src/hooks/__tests__/useThemeColor.test.ts) covers the following scenarios:

  1. Immediate application of the fallback/initial topLanguageColor.
  2. Successful asynchronous color extraction from an avatarUrl using FastAverageColor.
  3. Appropriate cleanup of generated CSS variables and disposal of the FastAverageColor instance upon component unmount.
  4. Race conditions, specifically ensuring that extracted colors are not applied to the DOM if the component unmounts before the asynchronous extraction promise resolves.
  5. Graceful error handling without application crashes if color extraction fails.

Result:
Test coverage for the src/hooks/useThemeColor.ts file has improved from 0% to 100% across statements, branches, and functions. This improves the overall codebase reliability and ensures dynamic theming features can be refactored with confidence.


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

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.

@vercel
Copy link
Copy Markdown

vercel bot commented Mar 27, 2026

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

Project Deployment Actions Updated (UTC)
github-user-summary Ready Ready Preview, Comment Mar 27, 2026 10:53am

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 27, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 52a15cb9-742b-487b-b442-39d69fe41338

📥 Commits

Reviewing files that changed from the base of the PR and between 7f098b2 and 391d810.

📒 Files selected for processing (1)
  • src/hooks/__tests__/useThemeColor.test.ts

📝 Walkthrough

Summary by CodeRabbit

  • テスト
    • テーマカラー機能の包括的なテスト suite を追加しました。フォールバック動作、非同期カラー抽出、クリーンアップ処理、エラーハンドリングを検証します。

Walkthrough

useThemeColor フック向けの Vitest + JSDOM テストを追加。色抽出とアクセント調整ライブラリをモックし、即時フォールバック適用、非同期抽出の反映、アンマウント時のクリーンアップ、レースコンディション、抽出失敗時の警告を検証します。

Changes

Cohort / File(s) Summary
useThemeColor テスト
src/hooks/__tests__/useThemeColor.test.ts
FastAverageColor.getColorAsync/destroyadjustAccentColor をモックし、フォールバックでの CSS 変数適用、avatarUrl による非同期色抽出→更新、アンマウント時の destroy と変数クリア、未解決 Promise 中のアンマウント(抽出結果を無視)、抽出失敗時の console.warn ログを含む5つのテストケースを追加。

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

size/M

Poem

🐰 ウサギより
色を抜いて、変数を流すよ
テストで確かめ、モックで守る
解除も無視も、ちゃんと処理
さあ品質の庭に跳びこもう!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title directly describes the main change: adding tests for the useThemeColor hook. It is specific, concise, and accurately reflects the changeset.
Description check ✅ Passed The description thoroughly explains what tests were added, which scenarios are covered, and the resulting improvement in test coverage. It is clearly related to the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch testing/use-theme-color-8717967491783105506

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 and usage tips.

Copy link
Copy Markdown

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

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 adds a comprehensive test suite for the useThemeColor hook, covering fallback colors, asynchronous extraction, and cleanup. The review feedback recommends removing an unused import, refactoring the fast-average-color mock into a class for better type safety, and extracting the adjustAccentColor mock into a variable to facilitate more detailed assertions.

// @vitest-environment jsdom
import { renderHook, waitFor } from "@testing-library/react";
import { useThemeColor } from "../useThemeColor";
import { describe, it, expect, vi, beforeEach, afterEach, Mock } from "vitest";
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 type is imported from vitest but is not used within the file. To maintain code cleanliness and avoid potential confusion, unused imports should be removed.

Suggested change
import { describe, it, expect, vi, beforeEach, afterEach, Mock } from "vitest";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";

Comment on lines +11 to +22
// Mock fast-average-color
vi.mock("fast-average-color", () => {
return {
FastAverageColor: function() {
// @ts-ignore
this.getColorAsync = mockGetColorAsync;
// @ts-ignore
this.destroy = mockDestroy;
return this;
}
};
});
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 current mock for fast-average-color uses a plain function and @ts-ignore to attach methods. This can be improved for better type safety and readability by using a class for the mock. This avoids the need for @ts-ignore and makes the mock's structure clearer and more robust.

vi.mock("fast-average-color", () => {
  return {
    FastAverageColor: class MockFastAverageColor {
      getColorAsync = mockGetColorAsync;
      destroy = mockDestroy;
    }
  };
});

Comment on lines +24 to +31
// Mock @/lib/color
vi.mock("@/lib/color", () => ({
adjustAccentColor: vi.fn().mockReturnValue({
accent: "mock-accent",
accentRgb: "100, 150, 200",
accentHover: "mock-accent-hover"
})
}));
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 for adjustAccentColor is defined inline, which prevents you from making assertions on how it's called within your tests. By extracting the mock function into a variable, you can write more specific and robust tests.

For example, you could then add a test case for when both topLanguageColor and avatarUrl are provided, ensuring the fallback is applied first and then correctly overridden by the async avatar color.

Here's how you could refactor the mock by defining a variable before this block and then using it in the mock definition:

// Define this before the mock
const mockAdjustAccentColor = vi.fn().mockReturnValue({
  accent: "mock-accent",
  accentRgb: "100, 150, 200",
  accentHover: "mock-accent-hover"
});

// Then update the mock definition
vi.mock("@/lib/color", () => ({
  adjustAccentColor: mockAdjustAccentColor
}));

With this change, you can then use mockAdjustAccentColor in your tests to assert call arguments and count, like expect(mockAdjustAccentColor).toHaveBeenCalledWith(...).

@coderabbitai coderabbitai bot added the size/M label Mar 27, 2026
Copy link
Copy Markdown

@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: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/hooks/__tests__/useThemeColor.test.ts`:
- Line 3: The import of useThemeColor should use the project path alias instead
of a relative path; replace the relative import of useThemeColor (the symbol
useThemeColor from "../useThemeColor") with the alias-based import (e.g.,
"@/hooks/useThemeColor") so it matches the repo's src/* alias convention and
linting rules.
- Line 4: Remove the unused Mock import from the top import list, delete the two
`@ts-ignore` comments and instead explicitly type the mocks used for
window.matchMedia and related handlers (e.g., declare a variable typed as
MediaQueryList | ReturnType<typeof vi.fn> or as vi.Mocked<MediaQueryList>), and
replace the any at line ~80 with a concrete type (such as MediaQueryList,
MediaQueryListEvent, or a vi.MockedFunction type) so the test uses proper
TypeScript types for the matchMedia mock and event listeners; update references
to the mocked functions to use vi.fn() with the chosen types (e.g., const
mockMatchMedia: MediaQueryList = { matches: false, addEventListener: vi.fn(),
removeEventListener: vi.fn(), ... } as unknown as MediaQueryList) and adjust
assertions to use those typed mocks.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: c9177859-dc33-4ca1-bcfa-b3dc40fca979

📥 Commits

Reviewing files that changed from the base of the PR and between e6bd6f9 and 7f098b2.

📒 Files selected for processing (1)
  • src/hooks/__tests__/useThemeColor.test.ts

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@is0692vs is0692vs merged commit 7906d1c into main Mar 29, 2026
7 checks passed
@is0692vs is0692vs deleted the testing/use-theme-color-8717967491783105506 branch March 29, 2026 10:17
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.

1 participant