Skip to content

🧪 Add tests for cardRenderer - #554

Open
is0692vs wants to merge 2 commits into
mainfrom
add-card-renderer-tests-15356029834693712644
Open

🧪 Add tests for cardRenderer#554
is0692vs wants to merge 2 commits into
mainfrom
add-card-renderer-tests-15356029834693712644

Conversation

@is0692vs

@is0692vs is0692vs commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

🎯 What: The src/lib/cardRenderer.tsx file was missing a dedicated test suite, which presented a testing gap given its reliance on external dependencies like @vercel/og (for ImageResponse), satori, and dynamic fetch calls for external font handling.

📊 Coverage: A new test suite was introduced at src/lib/__tests__/cardRenderer.test.tsx providing complete coverage across several distinct scenarios:

  • Successful card generation and validation of format headers for both SVG and PNG responses.
  • Accurate formatting and error code delegation for "Error Cards" matching the requested payload.
  • Proper delegation to the fetch API for retrieving valid font URLs while handling potential timeout, rejection, and fetch/status failures using mocked AbortController and fetch mechanisms.
  • Verification that local and untrusted remote fonts undergo thorough permission checks via the isTrustedFontUrl validator mapping logic before fallback occurs.
  • Memory management within the private font caching system (MAX_FONT_CACHE_SIZE), ensuring proper cache eviction logic prevents unbounded allocations when flooded with unique requests.

Result: Test coverage for src/lib/cardRenderer.tsx is now comprehensively accounted for, elevating line, branch, logic, and functional paths toward full protection against future regressions.


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

Greptile Summary

cardRenderer のSVG・PNG生成、エラーレスポンス、フォント取得、信頼性検査、キャッシュ退避を対象とする専用テストスイートを追加しています。大部分の主要分岐をモック環境で検証していますが、未信頼フォントのケースでは既定URLへのフォールバック自体が未検証です。

  • SVGおよびPNGの成功・エラーレスポンスを検証
  • フォント取得失敗とキャッシュ再利用・退避を検証
  • 未信頼フォントURLの検査呼び出しを検証

Confidence Score: 4/5

マージを妨げる問題はありませんが、未信頼フォントURLのフォールバックテストを具体化すると回帰検出力が向上します。

変更はテストのみで本番動作を変えませんが、未信頼URLのケースはバリデータ呼び出ししか確認しておらず、実際の取得先が既定フォントへ切り替わる契約を保護できていません。

Files Needing Attention: src/lib/tests/cardRenderer.test.tsx

Important Files Changed

Filename Overview
src/lib/tests/cardRenderer.test.tsx cardRenderer の主要経路を広くテストしているが、未信頼フォントが既定URLへ切り替わることを直接検証していない
Prompt To Fix All With AI
### Issue 1
src/lib/__tests__/cardRenderer.test.tsx:180
**フォールバック先が未検証**

このアサーションは `isTrustedFontUrl` の呼び出ししか確認していないため、未信頼URLをそのまま取得したり、誤ったURLへ切り替えたりする退行を検出できません。実際の `fetch` 引数などを使って、既定フォントURLが選択されたことも検証してください。

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Reviews (1): Last reviewed commit: "test: add test suite for cardRenderer.ts..." | Re-trigger Greptile

Greptile also left 1 inline comment on this PR.

Context used:

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

vercel Bot commented Aug 7, 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 Aug 7, 2026 6:55am

@coderabbitai

coderabbitai Bot commented Aug 7, 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: 46 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

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 Plus

Run ID: 22220b0b-f5bf-425a-8aa4-df224a7dcc0e

📥 Commits

Reviewing files that changed from the base of the PR and between eb95c48 and 10d6e1a.

📒 Files selected for processing (1)
  • src/lib/__tests__/cardRenderer.test.tsx

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.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Add Vitest coverage for cardRenderer rendering and font-fetch/cache behavior

🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Add dedicated Vitest suite for cardRenderer SVG/PNG success and error responses.
• Mock satori/@vercel/og to validate headers, status propagation, and response bodies.
• Cover font URL trust checks, fetch failures, and bounded font-cache eviction behavior.
Diagram

graph TD
  T["cardRenderer.test.tsx"] --> R["cardRenderer.tsx"] --> S["satori"] --> SVG["SVG string"]
  R --> OG["@vercel/og ImageResponse"] --> PNG["PNG response"]
  R --> V["isTrustedFontUrl"]
  R --> F[("fetch font")]
  R --> C["fontCache (Map)"]

  subgraph Legend
    direction LR
    _test["Test file"] ~~~ _mod["Module"] ~~~ _ext{{"External lib"}} ~~~ _io[("I/O")]
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use MSW for fetch mocking
  • ➕ More realistic request/response modeling (status, headers, delays).
  • ➕ Simplifies per-test setup for different fetch scenarios.
  • ➖ Adds dependency/setup overhead for a single-module unit test.
  • ➖ Less direct control over internal caching assertions without careful isolation.
2. Extract getFontData into a separately testable module
  • ➕ Enables more focused unit tests for caching/timeout/eviction without rendering concerns.
  • ➕ Reduces need to mock satori/@vercel/og for font-only scenarios.
  • ➖ Requires production refactor and API surface changes.
  • ➖ May be unnecessary if current test coverage is already sufficient.

Recommendation: Current approach (unit-testing cardRenderer with targeted mocks for satori, ImageResponse, fetch, and AbortController) is appropriate for fast, deterministic coverage of headers/status and cache behavior. Consider MSW only if future tests need richer network simulation, or extract getFontData if font logic grows substantially.

Files changed (1) +252 / -0

Tests (1) +252 / -0
cardRenderer.test.tsxAdd unit tests for SVG/PNG rendering and font fetch/cache logic +252/-0

Add unit tests for SVG/PNG rendering and font fetch/cache logic

• Introduces a Vitest suite that mocks satori and @vercel/og to validate successful and error card responses for both SVG and PNG formats. Adds coverage for font handling: trust validation via isTrustedFontUrl, fetch failure behavior, reuse of cached font promises, and eviction when the font cache exceeds MAX_FONT_CACHE_SIZE.

src/lib/tests/cardRenderer.test.tsx

@codecov

codecov Bot commented Aug 7, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

});

// Check that isTrustedFontUrl was called
expect(isTrustedFontUrl).toHaveBeenCalledWith(uniqueUrl, undefined);

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 フォールバック先が未検証

このアサーションは isTrustedFontUrl の呼び出ししか確認していないため、未信頼URLをそのまま取得したり、誤ったURLへ切り替えたりする退行を検出できません。実際の fetch 引数などを使って、既定フォントURLが選択されたことも検証してください。

Knowledge Base Used: Card Data Pipeline

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/lib/__tests__/cardRenderer.test.tsx
Line: 180

Comment:
**フォールバック先が未検証**

このアサーションは `isTrustedFontUrl` の呼び出ししか確認していないため、未信頼URLをそのまま取得したり、誤ったURLへ切り替えたりする退行を検出できません。実際の `fetch` 引数などを使って、既定フォントURLが選択されたことも検証してください。

**Knowledge Base Used:** [Card Data Pipeline](https://app.greptile.com/hiroki-org/-/custom-context/knowledge-base/hiroki-org/github-user-summary/-/docs/card-data-pipeline.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (3) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Non-camelCase test filename 📘 Rule violation ✧ Quality
Description
The newly added test file name cardRenderer.test.tsx includes a dot in its basename
(cardRenderer.test), which violates the camelCase-only filename policy for files introduced under
src/lib/. This can break filename lint rules and tooling conventions enforced by the repository.
Code

src/lib/tests/cardRenderer.test.tsx[1]

+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
Evidence
PR Compliance ID 226101 requires introduced/renamed files under src/lib/ to have a camelCase
basename containing only letters and digits. The added file path
src/lib/__tests__/cardRenderer.test.tsx has basename cardRenderer.test, which contains a . and
therefore does not meet the rule.

Rule 226101: Enforce camelCase file names in src/lib/
src/lib/tests/cardRenderer.test.tsx[1-1]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A new file was added under `src/lib/` whose basename is not camelCase because it contains a dot: `cardRenderer.test`.

## Issue Context
Compliance requires introduced/renamed files under `src/lib/` to use camelCase basenames consisting only of letters and digits.

## Fix Focus Areas
- src/lib/__tests__/cardRenderer.test.tsx[1-1]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Relative src imports in test 📘 Rule violation ✧ Quality
Description
The new test uses relative imports (e.g., ../cardRenderer) to import modules from within src/,
despite @/* being configured. This violates the requirement to use the @/ alias for src
imports and can lead to inconsistent import styles and brittle refactors.
Code

src/lib/tests/cardRenderer.test.tsx[R1-4]

+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
+import { renderCardResponse, renderErrorCardResponse } from "../cardRenderer";
+import type { CardData } from "../cardDataFetcher";
+import type { CardRenderOptions } from "../cardOptions";
Evidence
PR Compliance ID 226103 requires imports targeting code under src/ to use the @/ alias instead
of relative paths. The new test imports ../cardRenderer, ../cardDataFetcher, ../cardOptions,
and ../validators via relative paths, and the repo’s tsconfig.json defines @/*./src/*,
confirming the alias exists.

Rule 226103: Use @/ path alias for src imports in frontend code
src/lib/tests/cardRenderer.test.tsx[1-5]
tsconfig.json[1-34]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Imports in the new test file reference `src/` modules using relative paths instead of the configured `@/` alias.

## Issue Context
`tsconfig.json` configures `@/*` → `./src/*`, and compliance requires `@/` for imports targeting `src`.

## Fix Focus Areas
- src/lib/__tests__/cardRenderer.test.tsx[1-5]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Direct global fetch assignment 📘 Rule violation ▣ Testability
Description
The test directly assigns global.fetch = mockFetch (and also overwrites global.AbortController)
instead of using Vitest’s vi.stubGlobal, violating compliance requirements and risking global
state leakage between tests. Because these module-scope mutations are not restored, they can create
order-dependent, flaky behavior when the Vitest environment is reused across suites.
Code

src/lib/tests/cardRenderer.test.tsx[R28-30]

+const mockFetch = vi.fn();
+global.fetch = mockFetch;
+
Evidence
PR Compliance ID 226126 requires mocking fetch via vi.stubGlobal rather than direct assignment,
yet src/lib/__tests__/cardRenderer.test.tsx sets global.fetch = mockFetch, which is explicitly
disallowed. The same file also assigns to global.AbortController at module load time without
restoring either global, meaning other suites may observe mocked values depending on run order and
environment reuse; this is especially problematic for other tests that snapshot global.fetch as an
originalFetch at module initialization and later restore it in afterEach, since that “original”
may incorrectly capture the mocked version if this test runs first or leaves globals mutated.

Rule 226126: Use Vitest global fetch mocks via vi.stubGlobal
src/lib/tests/cardRenderer.test.tsx[28-30]
src/lib/tests/cardRenderer.test.tsx[28-42]
src/hooks/tests/useDashboardData.test.tsx[14-36]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Update `src/lib/__tests__/cardRenderer.test.tsx` to stop directly mutating `global.fetch` (and `global.AbortController`) at module scope and instead use Vitest’s global stubbing APIs with proper cleanup, so mocks do not leak between tests and the code complies with PR Compliance ID 226126.

## Issue Context
Compliance mandates mocking `fetch` via `vi.stubGlobal('fetch', ...)` (or an approved helper that uses it) rather than `global.fetch = ...`. The current test overwrites `global.fetch` and `global.AbortController` and never restores them, which can leak into other test files when the Vitest environment is reused; this can also break other suites that capture `global.fetch` as an `originalFetch` at module initialization and restore it in `afterEach`, because they may accidentally snapshot the mocked value.

## Fix Focus Areas
- src/lib/__tests__/cardRenderer.test.tsx[28-43]
- src/lib/__tests__/cardRenderer.test.tsx[45-57]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context used
✅ Compliance rules (platform): 30 rules

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Qodo Logo

@@ -0,0 +1,252 @@
import { describe, expect, it, vi, beforeEach, afterEach } 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.

Remediation recommended

1. Non-camelcase test filename 📘 Rule violation ✧ Quality

The newly added test file name cardRenderer.test.tsx includes a dot in its basename
(cardRenderer.test), which violates the camelCase-only filename policy for files introduced under
src/lib/. This can break filename lint rules and tooling conventions enforced by the repository.
Agent Prompt
## Issue description
A new file was added under `src/lib/` whose basename is not camelCase because it contains a dot: `cardRenderer.test`.

## Issue Context
Compliance requires introduced/renamed files under `src/lib/` to use camelCase basenames consisting only of letters and digits.

## Fix Focus Areas
- src/lib/__tests__/cardRenderer.test.tsx[1-1]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +1 to +4
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import { renderCardResponse, renderErrorCardResponse } from "../cardRenderer";
import type { CardData } from "../cardDataFetcher";
import type { CardRenderOptions } from "../cardOptions";

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Remediation recommended

2. Relative src imports in test 📘 Rule violation ✧ Quality

The new test uses relative imports (e.g., ../cardRenderer) to import modules from within src/,
despite @/* being configured. This violates the requirement to use the @/ alias for src
imports and can lead to inconsistent import styles and brittle refactors.
Agent Prompt
## Issue description
Imports in the new test file reference `src/` modules using relative paths instead of the configured `@/` alias.

## Issue Context
`tsconfig.json` configures `@/*` → `./src/*`, and compliance requires `@/` for imports targeting `src`.

## Fix Focus Areas
- src/lib/__tests__/cardRenderer.test.tsx[1-5]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +28 to +30
const mockFetch = vi.fn();
global.fetch = mockFetch;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Remediation recommended

3. Direct global fetch assignment 📘 Rule violation ▣ Testability

The test directly assigns global.fetch = mockFetch (and also overwrites global.AbortController)
instead of using Vitest’s vi.stubGlobal, violating compliance requirements and risking global
state leakage between tests. Because these module-scope mutations are not restored, they can create
order-dependent, flaky behavior when the Vitest environment is reused across suites.
Agent Prompt
## Issue description
Update `src/lib/__tests__/cardRenderer.test.tsx` to stop directly mutating `global.fetch` (and `global.AbortController`) at module scope and instead use Vitest’s global stubbing APIs with proper cleanup, so mocks do not leak between tests and the code complies with PR Compliance ID 226126.

## Issue Context
Compliance mandates mocking `fetch` via `vi.stubGlobal('fetch', ...)` (or an approved helper that uses it) rather than `global.fetch = ...`. The current test overwrites `global.fetch` and `global.AbortController` and never restores them, which can leak into other test files when the Vitest environment is reused; this can also break other suites that capture `global.fetch` as an `originalFetch` at module initialization and restore it in `afterEach`, because they may accidentally snapshot the mocked value.

## Fix Focus Areas
- src/lib/__tests__/cardRenderer.test.tsx[28-43]
- src/lib/__tests__/cardRenderer.test.tsx[45-57]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

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