Skip to content

🧪 [testing improvement] Add tests for validateSlug#882

Open
is0692vs wants to merge 2 commits into
stagingfrom
test-improve-validateslug-10952334015309556050
Open

🧪 [testing improvement] Add tests for validateSlug#882
is0692vs wants to merge 2 commits into
stagingfrom
test-improve-validateslug-10952334015309556050

Conversation

@is0692vs
Copy link
Copy Markdown
Contributor

@is0692vs is0692vs commented May 24, 2026

🎯 What: The testing gap in validateSlug function inside apps/api/src/routes/orgs.ts was addressed. The function was modified to be exported so it can be explicitly unit-tested.

📊 Coverage: A new describe block was added in apps/api/src/routes/__tests__/orgs.test.ts providing 100% path coverage for validateSlug. Scenarios covered include:

  • Non-string inputs
  • Bounds checking (length < 3, length > 40)
  • Trimming strings with whitespace
  • Lowercasing behavior
  • Invalid characters (via regex check)
  • Consecutive hyphens constraint
  • Valid slugs

Result: The improvement in test coverage prevents future regressions by explicitly pinning down the behavior of validateSlug. All unit tests passed without negatively affecting any part of the project.


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

Summary by CodeRabbit

  • Tests

    • Added comprehensive unit tests for slug validation, covering length constraints, invalid character detection, consecutive hyphens, and formatting requirements.
  • Refactor

    • Improved code organization for organization routes validation logic.

Review Change Stack

Greptile Summary

validateSlug 関数をエクスポートし、専用のユニットテストを追加する変更です。既存のロジックには一切手を加えず、テスト可能性の向上のみを目的としています。

  • apps/api/src/routes/orgs.tsvalidateSlug 関数に export を追加(1行のみ変更)
  • apps/api/src/routes/__tests__/orgs.test.ts — 非文字列入力・長さチェック・無効文字・連続ハイフン・正常値など全パスをカバーする describe ブロックを追加

Confidence Score: 4/5

既存の実装ロジックに変更はなく、テストの追加のみのため、マージしても安全です。

テスト自体は全コードパスをカバーしており論理的に正しいですが、長さチェックの境界値(ちょうど 3 文字・40 文字)が未テストのため、将来オフバイワンが混入した場合に検出できないリスクが残ります。

テストファイル apps/api/src/routes/__tests__/orgs.test.ts で境界値テストと beforeEach の配置を確認してください。

Important Files Changed

Filename Overview
apps/api/src/routes/tests/orgs.test.ts validateSlug のユニットテストを追加。全コードパスをカバーしているが、境界値テストが不足しており beforeEach の配置に可読性の改善余地あり。
apps/api/src/routes/orgs.ts validateSlug 関数に export キーワードを追加したのみ。関数本体に変更なし。

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[validateSlug入力] --> B{typeof slug === 'string'?}
    B -- No --> E1["'slug is required'"]
    B -- Yes --> C[trim + toLowerCase]
    C --> D{length < 3 OR length > 40?}
    D -- Yes --> E2["'slug must be 3–40 characters'"]
    D -- No --> F{SLUG_RE.test失敗?}
    F -- Yes --> E3["'slug must contain only...'"]
    F -- No --> G{includes '--'?}
    G -- Yes --> E4["'slug must not contain consecutive hyphens'"]
    G -- No --> H[null 返却]
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
apps/api/src/routes/__tests__/orgs.test.ts:28-30
`beforeEach` の位置がずれています。新しい `validateSlug` describe ブロックの追加により、`beforeEach` がネストされた describe の後に配置されました。Vitest/Jest では動作に影響しませんが、コードを読む際に可読性が下がります。`beforeEach``describe("orgs routes")` 直下の先頭に移動することを推奨します。

```suggestion
describe("orgs routes", () => {
  beforeEach(() => {
    vi.restoreAllMocks();
    vi.resetModules();
    mockDb = createMockDb();
  });

  describe("validateSlug", () => {
```

### Issue 2 of 2
apps/api/src/routes/__tests__/orgs.test.ts:38-47
**境界値テストが不足しています**

長さチェックのちょうど 3 文字・40 文字のテストが含まれていません。`<``>``<=``>=` に誤変更した場合にオフバイワンバグを検出できないリスクがあります。`validateSlug("abc")``"a".repeat(40)` のケースを追加することを推奨します。

Reviews (1): Last reviewed commit: "test: improve coverage for validateSlug ..." | Re-trigger Greptile

Greptile also left 2 inline comments on this PR.

is0692vs and others added 2 commits May 21, 2026 16:48
Release: staging -> main (2026-05-21 07:43)
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 May 24, 2026

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

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
open-shelf Ignored Ignored May 24, 2026 2:40am

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

@dosubot dosubot Bot added the javascript Pull requests that update javascript code label May 24, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 24, 2026

📝 Walkthrough

Walkthrough

The PR exports the validateSlug function from orgs.ts and adds comprehensive unit tests that cover slug validation rules including type checking, length boundaries, character restrictions, consecutive hyphens, and normalization behavior.

Changes

Slug Validation Refactoring

Layer / File(s) Summary
Export validateSlug function
apps/api/src/routes/orgs.ts
validateSlug is changed from a non-exported helper to an exported function, preserving its parameter and return types while making it available for external reuse.
Unit tests for validateSlug
apps/api/src/routes/__tests__/orgs.test.ts
Tests directly import and validate validateSlug behavior across invalid types, length boundaries (< 3, > 40), invalid characters (dots, @, spaces, leading/trailing hyphens), consecutive hyphens, and valid slugs with trimming and case normalization.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

  • Hiroki-org/OpenShelf#142: Both PRs focus on validateSlug behavior with overlapping coverage of length and hyphen validation rules.

Poem

🐰 A slug now ventures forth, no longer shy,
Exported wide for tests to verify.
With hyphens tamed and boundaries held tight,
This validation shines in unit-test light! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title mentions 'Add tests for validateSlug' which aligns with the main change of adding comprehensive test coverage for the validateSlug function, though the emoji and '[testing improvement]' tag add some noise.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ 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 test-improve-validateslug-10952334015309556050

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.

@github-actions github-actions Bot changed the base branch from main to staging May 24, 2026 02:40
@github-actions
Copy link
Copy Markdown

このリポジトリでは staging 先行フローを採用しています。PR のターゲットを staging に変更しました。staging で動作確認後、stagingmain の PR を作成してください。

@codecov
Copy link
Copy Markdown

codecov Bot commented May 24, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ All tests successful. No failed tests found.

📢 Thoughts on this report? Let us know!

Copy link
Copy Markdown
Contributor

@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 exports the validateSlug function and introduces unit tests to validate slug requirements, including length and character constraints. Feedback suggests enhancing the function by using constants for length limits, handling empty strings, and refining the regex. Additionally, the reviewer recommended adding boundary tests for length limits while keeping the test suite concise by removing redundant assertions.

Comment on lines +105 to 108
export function validateSlug(slug: unknown): string | null {
if (typeof slug !== "string") return "slug is required";
const s = slug.trim().toLowerCase();
if (s.length < 3 || s.length > 40) return "slug must be 3–40 characters";
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.

medium

The validateSlug function should return "slug is required" for empty or whitespace-only strings. Additionally, use pre-defined constants for the length limits (3 and 40) instead of hardcoding them to improve maintainability. The SLUG_RE regex contains a redundant branch for single characters that can be removed, and the error message for invalid characters should clarify that slugs cannot start or end with a hyphen.

Suggested change
export function validateSlug(slug: unknown): string | null {
if (typeof slug !== "string") return "slug is required";
const s = slug.trim().toLowerCase();
if (s.length < 3 || s.length > 40) return "slug must be 3–40 characters";
export function validateSlug(slug: unknown): string | null {
if (typeof slug !== "string") return "slug is required";
const s = slug.trim().toLowerCase();
if (s.length === 0) return "slug is required";
if (s.length < MIN_SLUG_LENGTH || s.length > MAX_SLUG_LENGTH) return "slug must be " + MIN_SLUG_LENGTH + "-" + MAX_SLUG_LENGTH + " characters";
References
  1. Use pre-defined constants for validation logic instead of hardcoding values to improve maintainability.

Comment on lines +79 to +87
it("returns null for valid slugs", () => {
expect(validateSlug("valid-slug")).toBeNull();
expect(validateSlug("valid")).toBeNull();
expect(validateSlug("v123")).toBeNull();
expect(validateSlug("123-abc")).toBeNull();
// Should trim and lowercase before validating
expect(validateSlug(" VALID-SLUG ")).toBeNull();
expect(validateSlug("Valid-Slug")).toBeNull();
});
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.

medium

Add boundary value tests for the slug length (exactly 3 and 40 characters). Comprehensive coverage for other normal success cases should be deferred to subsequent PRs to keep the test suite minimal.

    it("returns null for boundary length slugs", () => {
      expect(validateSlug("abc")).toBeNull();
      expect(validateSlug("a".repeat(40))).toBeNull();
    });
References
  1. Do not maintain redundant assertions in tests; keep them minimal.
  2. Defer comprehensive test coverage for all normal/success cases to subsequent PRs, provided that boundary tests have been added.

Comment on lines 28 to +30
describe("orgs routes", () => {

describe("validateSlug", () => {
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 beforeEach の位置がずれています。新しい validateSlug describe ブロックの追加により、beforeEach がネストされた describe の後に配置されました。Vitest/Jest では動作に影響しませんが、コードを読む際に可読性が下がります。beforeEachdescribe("orgs routes") 直下の先頭に移動することを推奨します。

Suggested change
describe("orgs routes", () => {
describe("validateSlug", () => {
describe("orgs routes", () => {
beforeEach(() => {
vi.restoreAllMocks();
vi.resetModules();
mockDb = createMockDb();
});
describe("validateSlug", () => {
Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/api/src/routes/__tests__/orgs.test.ts
Line: 28-30

Comment:
`beforeEach` の位置がずれています。新しい `validateSlug` describe ブロックの追加により、`beforeEach` がネストされた describe の後に配置されました。Vitest/Jest では動作に影響しませんが、コードを読む際に可読性が下がります。`beforeEach``describe("orgs routes")` 直下の先頭に移動することを推奨します。

```suggestion
describe("orgs routes", () => {
  beforeEach(() => {
    vi.restoreAllMocks();
    vi.resetModules();
    mockDb = createMockDb();
  });

  describe("validateSlug", () => {
```

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 +38 to +47
it("returns error if length < 3", () => {
expect(validateSlug("ab")).toBe("slug must be 3–40 characters");
expect(validateSlug("a")).toBe("slug must be 3–40 characters");
expect(validateSlug(" ab ")).toBe("slug must be 3–40 characters"); // Testing trim
});

it("returns error if length > 40", () => {
const longSlug = "a".repeat(41);
expect(validateSlug(longSlug)).toBe("slug must be 3–40 characters");
});
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 境界値テストが不足しています

長さチェックのちょうど 3 文字・40 文字のテストが含まれていません。<><=>= に誤変更した場合にオフバイワンバグを検出できないリスクがあります。validateSlug("abc")"a".repeat(40) のケースを追加することを推奨します。

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/api/src/routes/__tests__/orgs.test.ts
Line: 38-47

Comment:
**境界値テストが不足しています**

長さチェックのちょうど 3 文字・40 文字のテストが含まれていません。`<``>``<=``>=` に誤変更した場合にオフバイワンバグを検出できないリスクがあります。`validateSlug("abc")``"a".repeat(40)` のケースを追加することを推奨します。

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

javascript Pull requests that update javascript code size/M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant