Skip to content

🧪 [testing improvement] Add tests for handleRateLimit in apiUtils#365

Open
is0692vs wants to merge 1 commit into
mainfrom
test-handle-rate-limit-15266095550055349427
Open

🧪 [testing improvement] Add tests for handleRateLimit in apiUtils#365
is0692vs wants to merge 1 commit into
mainfrom
test-handle-rate-limit-15266095550055349427

Conversation

@is0692vs

@is0692vs is0692vs commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

🎯 What: This PR addresses a testing gap by adding unit tests for the handleRateLimit function in src/lib/apiUtils.ts.
📊 Coverage: The tests cover the happy path of parsing a valid X-RateLimit-Reset header and returning the associated timestamp, as well as the fallback logic when the header is missing or invalid.
Result: Test coverage for src/lib/apiUtils.ts has been improved, and the logic for parsing and throwing RateLimitError is now safeguarded against regressions.


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

Greptile Summary

このPRは src/lib/apiUtils.tshandleRateLimit 関数に対するユニットテストを追加します。正常系(有効な X-RateLimit-Reset ヘッダー)・ヘッダー欠損時のフォールバック・不正値(NaN)時のフォールバックの3ケースがカバーされています。

  • vi.useFakeTimers() + vi.setSystemTime(new Date(1000000)) で時刻を固定し、フォールバック計算(Math.floor(Date.now()/1000) + 3600 = 4600new Date(4600000))を決定論的にテストしている。
  • RateLimitError クラスがインポートされているものの、アサーションで使われておらず未使用となっている点が唯一の改善余地。

Confidence Score: 4/5

テスト専用ファイルの追加のみで、プロダクションコードへの変更はなく、安全にマージ可能。

追加されたテストはロジック的に正しく、タイムスタンプ計算も正確に検証されている。RateLimitError の未使用インポートとアサーションの型チェックの弱さは軽微な改善余地にとどまる。

特に注意が必要なファイルはなし。src/lib/__tests__/apiUtils.test.ts の未使用インポートを整理するとよい。

Important Files Changed

Filename Overview
src/lib/tests/apiUtils.test.ts handleRateLimit の3ケース(正常系・ヘッダーなし・不正値)をカバーするテストを追加。未使用の RateLimitError インポートが残っている。

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["handleRateLimit(res) 呼び出し"] --> B{"X-RateLimit-Reset\nヘッダーが存在するか?"}
    B -- "あり" --> C["parseInt(header, 10)"]
    B -- "なし" --> E["fallback:\nMath.floor(Date.now()/1000)+3600"]
    C --> D{"Number.isFinite\n(resetTimestamp)?"}
    D -- "true (例: 2000)" --> F["throw new RateLimitError(2000)\nresetAt = new Date(2000000)"]
    D -- "false (例: NaN from 'invalid')" --> E
    E --> G["throw new RateLimitError(4600)\nresetAt = new Date(4600000)"]

    style F fill:#d4edda,stroke:#28a745
    style G fill:#fff3cd,stroke:#ffc107
Loading
Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 2
src/lib/__tests__/apiUtils.test.ts:3
**未使用インポート: `RateLimitError`**

`RateLimitError` クラスがインポートされていますが、テスト内のアサーションでは文字列リテラル `'RateLimitError'` のみを使用しており、クラス自体は一切参照されていません。このインポートは削除するか、`expect.any(RateLimitError)``.toThrow(RateLimitError)` による `instanceof` チェックとして活用することを推奨します。文字列比較だと `name` プロパティを手動で設定したあらゆるエラーが誤ってパスしてしまうため、型安全性が低くなります。

### Issue 2 of 2
src/lib/__tests__/apiUtils.test.ts:74-77
**`RateLimitError` インポートを活用した `instanceof` チェックへの改善**

現在は `name: 'RateLimitError'` という文字列で確認しているため、同じ `name` プロパティを持つ別クラスでもテストがパスしてしまいます。インポート済みの `RateLimitError` を使い `.toThrow(RateLimitError)` で型を明示的に検証することで、より堅牢なアサーションになります。

```suggestion
      expect(() => handleRateLimit(res)).toThrow(RateLimitError);
      expect(() => handleRateLimit(res)).toThrowError(expect.objectContaining({
        resetAt: new Date(2000000)
      }));
```

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

Greptile also left 2 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.

@vercel

vercel Bot commented Jun 12, 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 Jun 12, 2026 6:49am

@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 →

@coderabbitai

coderabbitai Bot commented Jun 12, 2026

Copy link
Copy Markdown

Warning

Review limit reached

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

More reviews will be available in 49 minutes and 9 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more credits in the billing tab to continue.

⌛ How to resolve this issue?

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.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: eced18ce-d9e4-442e-b09f-459b531685dc

📥 Commits

Reviewing files that changed from the base of the PR and between a475ecb and d25f1d9.

📒 Files selected for processing (1)
  • src/lib/__tests__/apiUtils.test.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch test-handle-rate-limit-15266095550055349427

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.

@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 adds unit tests for the handleRateLimit utility function, covering scenarios with valid, missing, and invalid X-RateLimit-Reset headers. The reviewer suggested improving the robustness of these tests by explicitly asserting the error class using toThrow(RateLimitError) and catching the error to verify its custom properties, rather than relying on expect.objectContaining. Additionally, the reviewer recommended adding explicit return types to the test functions to ensure type safety.

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.

Comment on lines +70 to +78
it('should throw RateLimitError with timestamp from X-RateLimit-Reset header', () => {
const res = new Response(null, {
headers: { 'X-RateLimit-Reset': '2000' }
});
expect(() => handleRateLimit(res)).toThrowError(expect.objectContaining({
name: 'RateLimitError',
resetAt: new Date(2000000)
}));
});

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

Using expect.objectContaining inside toThrowError only asserts that the thrown value is an object with matching properties (like name: 'RateLimitError'). It does not guarantee that the thrown error is actually an instance of the RateLimitError class. To ensure type safety and prevent false positives, it is more robust to assert the error class using toThrow(RateLimitError) and then catch the error to verify its custom properties. Additionally, ensure functions have explicit return types to maintain type safety.

    it('should throw RateLimitError with timestamp from X-RateLimit-Reset header', (): void => {
      const res = new Response(null, {
        headers: { 'X-RateLimit-Reset': '2000' }
      });
      expect((): void => { handleRateLimit(res); }).toThrow(RateLimitError);
      try {
        handleRateLimit(res);
      } catch (error) {
        expect((error as RateLimitError).resetAt).toEqual(new Date(2000000));
      }
    });
References
  1. Maintain explicit return types for functions in TypeScript to ensure type safety and API clarity.

Comment on lines +80 to +86
it('should throw RateLimitError with fallback timestamp if header is missing', () => {
const res = new Response();
expect(() => handleRateLimit(res)).toThrowError(expect.objectContaining({
name: 'RateLimitError',
resetAt: new Date(4600000)
}));
});

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

Using expect.objectContaining inside toThrowError only asserts that the thrown value is an object with matching properties (like name: 'RateLimitError'). It does not guarantee that the thrown error is actually an instance of the RateLimitError class. To ensure type safety and prevent false positives, it is more robust to assert the error class using toThrow(RateLimitError) and then catch the error to verify its custom properties. Additionally, ensure functions have explicit return types to maintain type safety.

    it('should throw RateLimitError with fallback timestamp if header is missing', (): void => {
      const res = new Response();
      expect((): void => { handleRateLimit(res); }).toThrow(RateLimitError);
      try {
        handleRateLimit(res);
      } catch (error) {
        expect((error as RateLimitError).resetAt).toEqual(new Date(4600000));
      }
    });
References
  1. Maintain explicit return types for functions in TypeScript to ensure type safety and API clarity.

Comment on lines +88 to +96
it('should throw RateLimitError with fallback timestamp if header is invalid', () => {
const res = new Response(null, {
headers: { 'X-RateLimit-Reset': 'invalid' }
});
expect(() => handleRateLimit(res)).toThrowError(expect.objectContaining({
name: 'RateLimitError',
resetAt: new Date(4600000)
}));
});

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

Using expect.objectContaining inside toThrowError only asserts that the thrown value is an object with matching properties (like name: 'RateLimitError'). It does not guarantee that the thrown error is actually an instance of the RateLimitError class. To ensure type safety and prevent false positives, it is more robust to assert the error class using toThrow(RateLimitError) and then catch the error to verify its custom properties. Additionally, ensure functions have explicit return types to maintain type safety.

    it('should throw RateLimitError with fallback timestamp if header is invalid', (): void => {
      const res = new Response(null, {
        headers: { 'X-RateLimit-Reset': 'invalid' }
      });
      expect((): void => { handleRateLimit(res); }).toThrow(RateLimitError);
      try {
        handleRateLimit(res);
      } catch (error) {
        expect((error as RateLimitError).resetAt).toEqual(new Date(4600000));
      }
    });
References
  1. Maintain explicit return types for functions in TypeScript to ensure type safety and API clarity.

@codecov

codecov Bot commented Jun 12, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

import { handleErrorResponse, getAuthenticatedUser } from '../apiUtils';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { handleErrorResponse, getAuthenticatedUser, handleRateLimit } from '../apiUtils';
import { RateLimitError } from '../types';

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 未使用インポート: RateLimitError

RateLimitError クラスがインポートされていますが、テスト内のアサーションでは文字列リテラル 'RateLimitError' のみを使用しており、クラス自体は一切参照されていません。このインポートは削除するか、expect.any(RateLimitError).toThrow(RateLimitError) による instanceof チェックとして活用することを推奨します。文字列比較だと name プロパティを手動で設定したあらゆるエラーが誤ってパスしてしまうため、型安全性が低くなります。

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/lib/__tests__/apiUtils.test.ts
Line: 3

Comment:
**未使用インポート: `RateLimitError`**

`RateLimitError` クラスがインポートされていますが、テスト内のアサーションでは文字列リテラル `'RateLimitError'` のみを使用しており、クラス自体は一切参照されていません。このインポートは削除するか、`expect.any(RateLimitError)``.toThrow(RateLimitError)` による `instanceof` チェックとして活用することを推奨します。文字列比較だと `name` プロパティを手動で設定したあらゆるエラーが誤ってパスしてしまうため、型安全性が低くなります。

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 +74 to +77
expect(() => handleRateLimit(res)).toThrowError(expect.objectContaining({
name: 'RateLimitError',
resetAt: new Date(2000000)
}));

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 RateLimitError インポートを活用した instanceof チェックへの改善

現在は name: 'RateLimitError' という文字列で確認しているため、同じ name プロパティを持つ別クラスでもテストがパスしてしまいます。インポート済みの RateLimitError を使い .toThrow(RateLimitError) で型を明示的に検証することで、より堅牢なアサーションになります。

Suggested change
expect(() => handleRateLimit(res)).toThrowError(expect.objectContaining({
name: 'RateLimitError',
resetAt: new Date(2000000)
}));
expect(() => handleRateLimit(res)).toThrow(RateLimitError);
expect(() => handleRateLimit(res)).toThrowError(expect.objectContaining({
resetAt: new Date(2000000)
}));
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/lib/__tests__/apiUtils.test.ts
Line: 74-77

Comment:
**`RateLimitError` インポートを活用した `instanceof` チェックへの改善**

現在は `name: 'RateLimitError'` という文字列で確認しているため、同じ `name` プロパティを持つ別クラスでもテストがパスしてしまいます。インポート済みの `RateLimitError` を使い `.toThrow(RateLimitError)` で型を明示的に検証することで、より堅牢なアサーションになります。

```suggestion
      expect(() => handleRateLimit(res)).toThrow(RateLimitError);
      expect(() => handleRateLimit(res)).toThrowError(expect.objectContaining({
        resetAt: new Date(2000000)
      }));
```

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

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