Skip to content

test: add unit test for utilities - #441

Merged
Leo-rq-yu merged 8 commits into
InsForge:mainfrom
Yasir761:add/unit-tests
Oct 19, 2025
Merged

Leo-rq-yu merged 8 commits into
InsForge:mainfrom
Yasir761:add/unit-tests

Conversation

@Yasir761

@Yasir761 Yasir761 commented Oct 16, 2025 •

Copy link
Copy Markdown
Contributor

Summary

Added comprehensive unit tests for core utility modules.

These tests ensure stable behavior, validate environment handling, logging levels, and token verification edge cases.

How did you test this change?

Ran all unit tests locally using npx jest --config jest.config.cjs

Verified test suites passed, and fixed environment/config issues until all tests passed successfully

Summary by CodeRabbit

  • Tests

    • Added comprehensive unit tests for token verification, constants, helpers, logger, responses, SQL parsing, UUIDs, validations, and environment utilities.
  • Chores

    • Improved test configuration and development tooling; added Vitest type support.
  • Refactor

    • Normalized internal module imports and exposed the logger as a named export.

@coderabbitai

coderabbitai Bot commented Oct 16, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Removed .js extensions from internal imports, added a named export for the Winston logger, added Vitest aliases/types and a devDependency for tsconfig-paths, and added many unit tests for utilities, SQL parser, token verification, and environment helpers.

Changes

Cohort / File(s) Summary
Test infra & config
backend/package.json, backend/tsconfig.json, backend/vitest.config.ts
Added devDependency vite-tsconfig-paths; added "vitest" to TS types; added Vitest resolve.alias mappings: '@' → ./src and '@insforge/shared-schemas' → ../shared-schemas/src.
Import path tidy
backend/src/api/middleware/error.ts, backend/src/utils/cloud-token.ts, backend/src/utils/sql-parser.ts, backend/src/utils/validations.ts
Removed .js extensions from internal import specifiers (module resolution changes only; no logic changes).
Logger export change
backend/src/utils/logger.ts
Added a named export logger (keeps default export); no runtime configuration changes.
Unit tests — utilities & helpers
backend/tests/unit/constant.test.ts, backend/tests/unit/helpers.test.ts, backend/tests/unit/logger.test.ts, backend/tests/unit/response.test.ts, backend/tests/unit/uuid.test.ts, backend/tests/unit/validations.test.ts, backend/tests/unit/environment.test.ts
Added tests for constants, SQL→column type conversion, logger behavior, response helpers, UUID generation, validations, and environment helpers.
Unit tests — parser & tokens
backend/tests/unit/sql-parser.test.ts, backend/tests/unit/cloud-token.test.ts
Added SQL parser tests (comments, strings, splitting) and cloud token verification tests (mocked jose, payload/projectId validation).

Sequence Diagram(s)

No sequence diagram — changes don't modify runtime control flow.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I trimmed the .js from the trail,
Vitest found paths and wagged its tail,
Logger now waves as a named export bright,
Tests hop in to make sure all’s right,
A tiny carrot clap for this small tweak 🥕

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "test: add unit test for utilities" clearly and specifically describes the primary change in the changeset. The majority of the modifications consist of new unit test files for various utility modules (cloud-token, logger, response, sql-parser, uuid, validations, environment, helpers, and constants), along with supporting configuration changes to enable these tests. The title accurately captures this main objective and follows conventional commit format. A teammate scanning the git history would immediately understand that this PR adds unit tests for utility functions, making it clear and unambiguous.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 4

🧹 Nitpick comments (5)
backend/src/utils/logger.ts (1)

3-3: Minor: Fix double space before logger.

The named export is a good addition for import flexibility, but there's an extra space between const and logger.

Apply this diff:

-export const  logger = winston.createLogger({
+export const logger = winston.createLogger({
backend/tsconfig.json (1)

19-19: Minor: Inconsistent spacing in types array.

Adding "jest" to the types array is correct for enabling Jest type definitions, but there's inconsistent spacing in the array.

Apply this diff for consistency:

-    "types": ["node","jest" ]
+    "types": ["node", "jest"]
backend/tests/unit/helpers.test.ts (1)

1-50: LGTM! Consider minor formatting improvement.

The test suite comprehensively covers all SQL type conversions with good edge case handling. The logic is correct and matches the implementation in backend/src/utils/helpers.ts.

Optional: For consistency with typical JavaScript/TypeScript formatting, consider adding spaces after commas in arrays on lines 16, 23, and 41:

-    const integers = ['integer','bigint','smallint','int','int2','int4','serial','serial2','serial4','serial8','smallserial','bigserial'];
+    const integers = ['integer', 'bigint', 'smallint', 'int', 'int2', 'int4', 'serial', 'serial2', 'serial4', 'serial8', 'smallserial', 'bigserial'];

-    const floats = ['double precision','real','numeric','float','float4','float8','decimal'];
+    const floats = ['double precision', 'real', 'numeric', 'float', 'float4', 'float8', 'decimal'];

-    const strings = ['text','varchar','char','character','character varying'];
+    const strings = ['text', 'varchar', 'char', 'character', 'character varying'];
backend/jest.config.cjs (2)

19-36: Transform configuration is correct for TypeScript testing.

The ts-jest configuration appropriately overrides the tsconfig settings for Jest's CommonJS environment. The module: 'commonjs' setting is required for Jest, and the other settings enable proper TypeScript module resolution.

Note: The paths configuration (lines 30-33) duplicates logic from moduleNameMapper (lines 6-14). While this duplication is necessary for both Jest module resolution and TypeScript compilation, consider documenting that these must be kept in sync, or extract to a shared configuration if maintenance becomes an issue.


38-42: Consider enhancing test configuration.

The current configuration is functional, but consider the following optional improvements as your test suite matures:

  1. Enable roots option: If your tests are organized under tests/unit, uncomment line 39 to scope test discovery.

  2. Add test file patterns: Explicitly specify test file patterns for clarity:

testMatch: ['**/__tests__/**/*.(test|spec).ts', '**/?(*.)+(spec|test).ts'],
  1. Configure coverage collection: Add coverage configuration if not already in package.json:
collectCoverageFrom: [
  'src/**/*.ts',
  '!src/**/*.d.ts',
  '!src/**/__tests__/**',
],
  1. Add global test setup: If needed, configure global test setup:
setupFilesAfterEnv: ['<rootDir>/tests/setup.ts'],
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e7e97c1 and 6277401.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (17)
  • backend/jest.config.cjs (1 hunks)
  • backend/package.json (2 hunks)
  • backend/src/api/middleware/error.ts (1 hunks)
  • backend/src/utils/cloud-token.ts (1 hunks)
  • backend/src/utils/logger.ts (1 hunks)
  • backend/src/utils/sql-parser.ts (1 hunks)
  • backend/src/utils/validations.ts (1 hunks)
  • backend/tests/unit/cloud-token.test.ts (1 hunks)
  • backend/tests/unit/constant.test.ts (1 hunks)
  • backend/tests/unit/enviroment.test.ts (1 hunks)
  • backend/tests/unit/helpers.test.ts (1 hunks)
  • backend/tests/unit/logger.test.ts (1 hunks)
  • backend/tests/unit/response.test.ts (1 hunks)
  • backend/tests/unit/sql-parser.test.ts (1 hunks)
  • backend/tests/unit/uuid.test.ts (1 hunks)
  • backend/tests/unit/validations.test.ts (1 hunks)
  • backend/tsconfig.json (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions

Files:

  • backend/src/utils/sql-parser.ts
  • backend/tests/unit/cloud-token.test.ts
  • backend/tests/unit/uuid.test.ts
  • backend/src/utils/cloud-token.ts
  • backend/tests/unit/helpers.test.ts
  • backend/tests/unit/constant.test.ts
  • backend/tests/unit/enviroment.test.ts
  • backend/src/utils/validations.ts
  • backend/tests/unit/validations.test.ts
  • backend/src/api/middleware/error.ts
  • backend/tests/unit/sql-parser.test.ts
  • backend/tests/unit/logger.test.ts
  • backend/tests/unit/response.test.ts
  • backend/src/utils/logger.ts
backend/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)

Files:

  • backend/src/utils/sql-parser.ts
  • backend/src/utils/cloud-token.ts
  • backend/src/utils/validations.ts
  • backend/src/api/middleware/error.ts
  • backend/src/utils/logger.ts
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

React components and TypeScript types/interfaces must use PascalCase

Files:

  • backend/src/utils/sql-parser.ts
  • backend/tests/unit/cloud-token.test.ts
  • backend/tests/unit/uuid.test.ts
  • backend/src/utils/cloud-token.ts
  • backend/tests/unit/helpers.test.ts
  • backend/tests/unit/constant.test.ts
  • backend/tests/unit/enviroment.test.ts
  • backend/src/utils/validations.ts
  • backend/tests/unit/validations.test.ts
  • backend/src/api/middleware/error.ts
  • backend/tests/unit/sql-parser.test.ts
  • backend/tests/unit/logger.test.ts
  • backend/tests/unit/response.test.ts
  • backend/src/utils/logger.ts
**/[a-z][a-z0-9-]*.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Utility files should use kebab-case or camelCase (kebab-case validated here)

Files:

  • backend/src/utils/sql-parser.ts
  • backend/tests/unit/cloud-token.test.ts
  • backend/tests/unit/uuid.test.ts
  • backend/src/utils/cloud-token.ts
  • backend/tests/unit/helpers.test.ts
  • backend/tests/unit/constant.test.ts
  • backend/tests/unit/enviroment.test.ts
  • backend/src/utils/validations.ts
  • backend/tests/unit/validations.test.ts
  • backend/src/api/middleware/error.ts
  • backend/tests/unit/sql-parser.test.ts
  • backend/tests/unit/logger.test.ts
  • backend/tests/unit/response.test.ts
  • backend/src/utils/logger.ts
backend/src/api/**/*.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/api/**/*.ts: Implement authentication and error-handling middleware
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints

Files:

  • backend/src/api/middleware/error.ts
🧠 Learnings (1)
📚 Learning: 2025-10-15T18:18:47.505Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.505Z
Learning: Applies to backend/src/**/*.{ts,tsx} : Return consistent API responses using utility functions

Applied to files:

  • backend/tests/unit/response.test.ts
🧬 Code graph analysis (8)
backend/tests/unit/cloud-token.test.ts (2)
backend/src/utils/cloud-token.ts (1)
  • verifyCloudToken (9-39)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/tests/unit/helpers.test.ts (1)
backend/src/utils/helpers.ts (1)
  • convertSqlTypeToColumnType (3-49)
backend/tests/unit/constant.test.ts (1)
backend/src/utils/constants.ts (1)
  • ADMIN_ID (1-1)
backend/tests/unit/enviroment.test.ts (1)
backend/src/utils/environment.ts (4)
  • isCloudEnvironment (9-13)
  • isOAuthSharedKeysAvailable (19-21)
  • isDevelopment (26-28)
  • isProduction (33-35)
backend/tests/unit/validations.test.ts (2)
backend/src/utils/validations.ts (7)
  • validateEmail (4-6)
  • validateIdentifier (27-47)
  • isValidIdentifier (54-56)
  • validateTableName (65-79)
  • getIdentifierErrorMessage (87-95)
  • escapeSqlLikePattern (110-112)
  • escapeRegexPattern (127-129)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/tests/unit/sql-parser.test.ts (1)
backend/src/utils/sql-parser.ts (1)
  • parseSQLStatements (16-63)
backend/tests/unit/logger.test.ts (1)
backend/src/utils/logger.ts (1)
  • logger (3-11)
backend/tests/unit/response.test.ts (1)
backend/src/utils/response.ts (3)
  • successResponse (22-24)
  • errorResponse (27-42)
  • paginatedResponse (45-62)
🔇 Additional comments (16)
backend/package.json (2)

15-15: LGTM!

The test script is correctly configured to run Jest unit tests with the CommonJS config file.


68-68: Jest 30.2.0 and ts-jest 29.4.5 are compatible. ts-jest 29.x declares jest ^29 || ^30 as a peer dependency. Ensure your Node, TypeScript, and jsdom versions meet Jest 30’s minimum requirements and monitor for ts-jest version-checker warnings if other @jest/* packages mismatch.

backend/src/utils/sql-parser.ts (1)

3-3: LGTM!

Import path normalization looks good and aligns with the project-wide removal of .js extensions.

backend/src/utils/validations.ts (1)

1-2: LGTM!

Import path normalization is consistent with the project-wide changes to remove .js extensions.

backend/src/api/middleware/error.ts (1)

4-5: LGTM!

Import path normalization is consistent with the project-wide removal of .js extensions.

backend/tests/unit/uuid.test.ts (1)

1-21: LGTM!

The test suite provides good coverage for the generateUUID utility:

  • Type validation ensures it returns a string
  • Regex validation confirms UUID v4 format compliance
  • Uniqueness check with 10 samples verifies non-deterministic generation

The test structure follows Jest best practices.

backend/src/utils/cloud-token.ts (1)

2-3: LGTM!

Import path normalization aligns with the project-wide standardization to remove .js extensions.

backend/tests/unit/constant.test.ts (1)

1-7: LGTM!

The test correctly verifies the ADMIN_ID constant value. The implementation is clean and follows the project's coding guidelines.

backend/tests/unit/response.test.ts (1)

1-57: LGTM!

The test suite comprehensively covers all response utility functions with proper mocking of Express Response objects. The tests correctly verify status codes, response bodies, and headers for success, error, and paginated responses. As per coding guidelines, the implementation uses consistent API response patterns.

backend/tests/unit/enviroment.test.ts (1)

8-58: LGTM!

The test suite properly covers all environment utility functions with correct setup and teardown of process.env. Tests verify both positive and negative cases for cloud environment detection, OAuth key availability, and environment mode detection.

backend/tests/unit/sql-parser.test.ts (2)

19-40: Clarify the expected comment handling behavior.

The comments on lines 25 and 37 state "Parser returns everything as one statement including comments," which seems to contradict the purpose of a statement parser. The tests use toHaveLength(1) and toContain, suggesting the parser may not be splitting statements as expected.

Based on the implementation in backend/src/utils/sql-parser.ts, the parser uses splitSqlQuery and filters out comment-only statements. The test expectations should match this behavior. Verify whether:

  1. Comments within statements are preserved (expected)
  2. Multiple statements are properly split (expected based on line 5-17)
  3. Comment-only content is filtered out (expected based on line 53-61)

5-17: Inconsistent expectations for trailing semicolons
The “splits multiple statements” test strips semicolons, but the “handles semicolons inside string literals” test expects a trailing semicolon. Confirm the intended behavior and align the tests and comments accordingly.

backend/tests/unit/cloud-token.test.ts (1)

1-40: LGTM!

The test suite properly mocks the jose library and tests both successful token verification and error cases. The tests correctly verify that:

  1. Valid tokens return the expected payload and projectId
  2. Missing or mismatched projectIds throw AppError

The mocking strategy is sound and the test coverage is appropriate.

backend/tests/unit/validations.test.ts (1)

1-79: LGTM!

The test suite comprehensively covers all validation utilities with proper edge case testing. Tests correctly verify:

  • Email format validation
  • Identifier constraints (non-empty, no quotes/control chars)
  • Table name restrictions (no system tables starting with _)
  • Error message generation
  • SQL LIKE and regex pattern escaping

The tests properly use AppError assertions where expected and follow the project's coding guidelines.

backend/jest.config.cjs (2)

6-14: Approve moduleNameMapper configuration

The mapping for @insforge/shared-schemas correctly points to shared-schemas/src/index.ts.


1-43: Verify ts-jest support for Jest 30. Detected jest ^30.2.0 and ts-jest ^29.4.5 – confirm ts-jest v29’s peerDependencies allow Jest v30 (e.g. inspect node_modules/ts-jest/package.json or ts-jest docs).

Comment thread backend/tests/unit/environment.test.ts Resolved
Comment thread backend/tests/unit/logger.test.ts Resolved
Comment thread backend/tests/unit/logger.test.ts Resolved
Comment thread backend/tests/unit/sql-parser.test.ts Resolved

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 3

♻️ Duplicate comments (1)
backend/tests/unit/sql-parser.test.ts (1)

63-74: Strengthen the test assertions.

The current assertions are too weak and don't properly verify the expected behavior. The input contains two SQL statements (SELECT and INSERT), so the test should explicitly verify that exactly two statements are returned and check both statements' content.

Apply this diff to strengthen the assertions:

     const result = parseSQLStatements(sql);
-   
-    expect(result.length).toBeGreaterThan(0);
-    expect(result[0]).toContain('SELECT * FROM users');
-    expect(result[result.length - 1] || result[0]).toContain('INSERT INTO users');
+    
+    expect(result).toHaveLength(2);
+    expect(result[0]).toContain('SELECT * FROM users');
+    expect(result[1]).toContain('INSERT INTO users');
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6277401 and d57c9c1.

📒 Files selected for processing (2)
  • backend/tests/unit/logger.test.ts (1 hunks)
  • backend/tests/unit/sql-parser.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/tests/unit/logger.test.ts
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions

Files:

  • backend/tests/unit/sql-parser.test.ts
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

React components and TypeScript types/interfaces must use PascalCase

Files:

  • backend/tests/unit/sql-parser.test.ts
**/[a-z][a-z0-9-]*.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Utility files should use kebab-case or camelCase (kebab-case validated here)

Files:

  • backend/tests/unit/sql-parser.test.ts
🧬 Code graph analysis (1)
backend/tests/unit/sql-parser.test.ts (1)
backend/src/utils/sql-parser.ts (1)
  • parseSQLStatements (16-63)
🔇 Additional comments (3)
backend/tests/unit/sql-parser.test.ts (3)

5-17: LGTM!

The test correctly verifies that the parser splits multiple SQL statements and trims trailing semicolons from each statement.


49-51: LGTM!

The test correctly verifies that the parser throws an error when given empty input, matching the implementation's validation logic.


53-61: LGTM!

The test correctly verifies that the parser returns an empty array when given SQL containing only comments, as the implementation filters out comment-only statements.

Comment thread backend/tests/unit/sql-parser.test.ts Resolved
Comment thread backend/tests/unit/sql-parser.test.ts Resolved
Comment thread backend/tests/unit/sql-parser.test.ts Resolved
@Yasir761 Yasir761 mentioned this pull request Oct 16, 2025
@tonychang04 tonychang04 linked an issue Oct 16, 2025 that may be closed by this pull request
@Leo-rq-yu

Copy link
Copy Markdown
Contributor

@Yasir761 Really appreciate your contribution! We already had the Vitest package installed for testing. I may not have the context, but I want you to clarify why you preferred to add the jest package for unit testing. Also, there is a misspelling in the file name in your PR Please fix that as well!

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 0

🧹 Nitpick comments (2)
backend/tests/unit/environment.test.ts (2)

11-17: Consider using afterEach instead of afterAll for better test isolation.

While the current approach works, using afterEach to restore the environment after each test ensures complete isolation and prevents potential cross-test pollution.

Apply this diff:

   beforeEach(() => {
     process.env = { ...OLD_ENV };
   });
 
-  afterAll(() => {
+  afterEach(() => {
     process.env = OLD_ENV;
   });

19-27: Add edge case tests for empty and whitespace-only values.

The source implementation explicitly checks trim().length > 0, but the tests don't verify behavior for empty strings or whitespace-only values.

Add these test cases:

  test('isCloudEnvironment returns false if AWS_INSTANCE_PROFILE_NAME is empty', () => {
    process.env.AWS_INSTANCE_PROFILE_NAME = '';
    expect(isCloudEnvironment()).toBe(false);
  });

  test('isCloudEnvironment returns false if AWS_INSTANCE_PROFILE_NAME is whitespace only', () => {
    process.env.AWS_INSTANCE_PROFILE_NAME = '   ';
    expect(isCloudEnvironment()).toBe(false);
  });
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 72e329e and 53b83ca.

📒 Files selected for processing (1)
  • backend/tests/unit/environment.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions

Files:

  • backend/tests/unit/environment.test.ts
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

React components and TypeScript types/interfaces must use PascalCase

Files:

  • backend/tests/unit/environment.test.ts
**/[a-z][a-z0-9-]*.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Utility files should use kebab-case or camelCase (kebab-case validated here)

Files:

  • backend/tests/unit/environment.test.ts
🧠 Learnings (1)
📓 Common learnings
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.505Z
Learning: Applies to tests/**/*.{test,spec}.{ts,tsx} : Mock external dependencies appropriately in tests
🧬 Code graph analysis (1)
backend/tests/unit/environment.test.ts (1)
backend/src/utils/environment.ts (4)
  • isCloudEnvironment (9-13)
  • isOAuthSharedKeysAvailable (19-21)
  • isDevelopment (26-28)
  • isProduction (33-35)
🔇 Additional comments (2)
backend/tests/unit/environment.test.ts (2)

29-35: LGTM!

The test correctly verifies that isOAuthSharedKeysAvailable delegates to isCloudEnvironment for both true and false cases.


37-57: LGTM!

Both isDevelopment and isProduction tests comprehensively cover all branches:

  • Explicit 'development' and 'production' values
  • Opposite environment values
  • Undefined/missing NODE_ENV edge case

The test logic correctly matches the source implementations.

@Yasir761

Copy link
Copy Markdown
Contributor Author

@Leo-rq-yu, thanks for catching that!
I’ve fixed the filename typo.

Reason why I chose Jest: TypeScript-compatible and simple to configure without extra tooling. Jest’s ecosystem (mocks, spies, clear mocks, etc.) made writing unit tests for backend utilities easier, but if the team prefers to stay consistent with Vitest, I can migrate all the test files to Vitest

@Leo-rq-yu

Copy link
Copy Markdown
Contributor

I understand that Jest is more mature and stable, but since we have already installed Vitest and are using Vite + React, I believe we would like to be consistent with the Vite ecosystem. Vitest also only reruns tests affected by code changes, making it beneficial for a better development experience. Really appreciate your understanding!

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 4

♻️ Duplicate comments (1)
backend/tests/unit/logger.test.ts (1)

5-7: Test doesn't independently verify the fallback behavior.

The assertion uses the same process.env.LOG_LEVEL || 'info' expression as the logger initialization, so it always passes and doesn't actually verify the fallback logic. Split this into two tests: one that sets LOG_LEVEL to a specific value (e.g., 'debug') and verifies it's used, and another that explicitly unsets LOG_LEVEL and verifies the 'info' default. You'll need to reload the logger module between tests to observe the behavior.

🧹 Nitpick comments (5)
backend/tests/unit/validations.test.ts (1)

24-36: Consider testing control characters edge case.

The test suite covers empty identifiers and quotes, but the implementation's error message mentions "control characters (tabs, newlines, etc.)" which aren't explicitly tested. Adding a test case for control characters would improve coverage.

Example additional test:

test('identifier with control characters throws AppError', () => {
  expect(() => validateIdentifier('table\nname')).toThrow(AppError);
  expect(() => validateIdentifier('table\tname')).toThrow(AppError);
});
backend/tests/unit/environment.test.ts (1)

20-28: Add edge case tests for empty and whitespace-only strings.

The source implementation checks trim().length > 0, but the tests don't cover the edge cases where AWS_INSTANCE_PROFILE_NAME is an empty string or contains only whitespace. Both should return false.

Add these test cases to improve coverage:

   it('isCloudEnvironment returns false if AWS_INSTANCE_PROFILE_NAME is missing', () => {
     delete process.env.AWS_INSTANCE_PROFILE_NAME;
     expect(isCloudEnvironment()).toBe(false);
   });
+
+  it('isCloudEnvironment returns false if AWS_INSTANCE_PROFILE_NAME is empty', () => {
+    process.env.AWS_INSTANCE_PROFILE_NAME = '';
+    expect(isCloudEnvironment()).toBe(false);
+  });
+
+  it('isCloudEnvironment returns false if AWS_INSTANCE_PROFILE_NAME is whitespace only', () => {
+    process.env.AWS_INSTANCE_PROFILE_NAME = '   ';
+    expect(isCloudEnvironment()).toBe(false);
+  });
backend/tests/unit/logger.test.ts (1)

15-21: Consider testing actual logging behavior rather than just spy invocation.

The test spies on logger.error, mocks it, calls it, and verifies the spy was called—this is circular and doesn't validate real behavior. Consider either removing the spy and just verifying no exceptions are thrown (similar to lines 9-13), or capturing the actual logged output to verify it contains the expected error message or format.

For example, simplify to a non-throwing assertion:

-  it('should call logger.error when logging errors', () => {
-  const error = new Error('Test error');
-  const logSpy = vi.spyOn(logger, 'error').mockImplementation((infoObject: object) => logger);
-  logger.error(error);
-  expect(logSpy).toHaveBeenCalled();
-  logSpy.mockRestore();
-});
+  it('should log errors without throwing', () => {
+    const error = new Error('Test error');
+    expect(() => logger.error(error)).not.toThrow();
+  });
backend/tests/unit/cloud-token.test.ts (2)

25-25: Simplify mock type casting.

The type casting (jwtVerify as unknown as ReturnType<typeof vi.fn>) is unnecessarily verbose. Consider using vi.mocked(jwtVerify) if types are set up correctly, or simply cast to any for test mocks.

Example:

vi.mocked(jwtVerify).mockResolvedValue({
  payload: { projectId: 'project_123', user: 'testUser' },
});

Also applies to: 35-35


34-40: Test coverage gap: add case for actual projectId mismatch.

The test description says "mismatch or missing" but only covers the missing projectId scenario. You should add a test case where projectId is present but different from the expected PROJECT_ID to ensure the validation logic correctly rejects mismatched tokens.

Add this test case:

it('throws AppError if project ID mismatches expected', async () => {
  vi.mocked(jwtVerify).mockResolvedValue({
    payload: { projectId: 'wrong_project', user: 'testUser' },
  });

  await expect(verifyCloudToken('token')).rejects.toThrow(AppError);
  await expect(verifyCloudToken('token')).rejects.toThrow('Project ID mismatch');
});
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 53b83ca and 7ac348b.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (12)
  • backend/package.json (1 hunks)
  • backend/tests/unit/cloud-token.test.ts (1 hunks)
  • backend/tests/unit/constant.test.ts (1 hunks)
  • backend/tests/unit/environment.test.ts (1 hunks)
  • backend/tests/unit/helpers.test.ts (1 hunks)
  • backend/tests/unit/logger.test.ts (1 hunks)
  • backend/tests/unit/response.test.ts (1 hunks)
  • backend/tests/unit/sql-parser.test.ts (1 hunks)
  • backend/tests/unit/uuid.test.ts (1 hunks)
  • backend/tests/unit/validations.test.ts (1 hunks)
  • backend/tsconfig.json (1 hunks)
  • backend/vitest.config.ts (2 hunks)
✅ Files skipped from review due to trivial changes (3)
  • backend/tests/unit/helpers.test.ts
  • backend/package.json
  • backend/tests/unit/constant.test.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • backend/tests/unit/sql-parser.test.ts
  • backend/tests/unit/response.test.ts
  • backend/tests/unit/uuid.test.ts
  • backend/tsconfig.json
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions

Files:

  • backend/tests/unit/environment.test.ts
  • backend/tests/unit/cloud-token.test.ts
  • backend/tests/unit/logger.test.ts
  • backend/tests/unit/validations.test.ts
  • backend/vitest.config.ts
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

React components and TypeScript types/interfaces must use PascalCase

Files:

  • backend/tests/unit/environment.test.ts
  • backend/tests/unit/cloud-token.test.ts
  • backend/tests/unit/logger.test.ts
  • backend/tests/unit/validations.test.ts
  • backend/vitest.config.ts
**/[a-z][a-z0-9-]*.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Utility files should use kebab-case or camelCase (kebab-case validated here)

Files:

  • backend/tests/unit/environment.test.ts
  • backend/tests/unit/cloud-token.test.ts
  • backend/tests/unit/logger.test.ts
  • backend/tests/unit/validations.test.ts
  • backend/vitest.config.ts
🧬 Code graph analysis (5)
backend/tests/unit/environment.test.ts (1)
backend/src/utils/environment.ts (4)
  • isCloudEnvironment (9-13)
  • isOAuthSharedKeysAvailable (19-21)
  • isDevelopment (26-28)
  • isProduction (33-35)
backend/tests/unit/cloud-token.test.ts (2)
backend/src/utils/cloud-token.ts (1)
  • verifyCloudToken (9-39)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/tests/unit/logger.test.ts (1)
backend/src/utils/logger.ts (1)
  • logger (3-11)
backend/tests/unit/validations.test.ts (2)
backend/src/utils/validations.ts (7)
  • validateEmail (4-6)
  • validateIdentifier (27-47)
  • isValidIdentifier (54-56)
  • validateTableName (65-79)
  • getIdentifierErrorMessage (87-95)
  • escapeSqlLikePattern (110-112)
  • escapeRegexPattern (127-129)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/vitest.config.ts (1)
eslint.config.js (1)
  • __dirname (12-12)
🔇 Additional comments (10)
backend/tests/unit/validations.test.ts (1)

13-80: Excellent test coverage for validation utilities!

The test suite is well-structured with clear test names, proper use of Vitest's API, and comprehensive coverage of the main validation functions. The tests effectively verify both success and error paths, and the organization with describe blocks makes the suite easy to navigate.

backend/tests/unit/environment.test.ts (5)

1-7: LGTM! Vitest imports and structure are correct.

The imports are clean, and using Vitest aligns with the team's preference for consistency with the Vite ecosystem as discussed in the PR comments.


9-18: LGTM! Proper environment isolation pattern.

The setup/teardown correctly isolates environment variables between tests and restores the original state after all tests complete. This follows best practices for testing code that depends on process.env.


30-36: LGTM! Tests correctly verify the delegation.

The tests correctly verify that isOAuthSharedKeysAvailable mirrors isCloudEnvironment behavior. While the function simply delegates, testing the public API explicitly is good practice.


38-47: LGTM! Comprehensive coverage of isDevelopment logic.

The tests correctly validate all branches of the implementation: explicit 'development', explicit 'production', and the default behavior when NODE_ENV is unset.


49-58: LGTM! Complete validation of isProduction logic.

The tests correctly validate the implementation: returns true only for 'production', and false for all other cases including when NODE_ENV is unset.

backend/tests/unit/logger.test.ts (2)

1-2: LGTM! Imports are correct.

The named logger export matches the utility implementation, and Vitest is the team's preferred test framework for consistency with the Vite ecosystem.


9-13: LGTM! Valid smoke test.

The test correctly verifies that basic logging methods don't throw exceptions.

backend/tests/unit/cloud-token.test.ts (2)

6-10: Mock setup is correct.

The jose module mocks are properly configured for the test scenarios.


12-22: Environment handling is correct.

The test properly isolates environment variables using beforeEach/afterAll, which is safe given the sequential test execution configured in vitest.config.ts.

Comment thread backend/tests/unit/cloud-token.test.ts Resolved
Comment thread backend/tests/unit/logger.test.ts Resolved
Comment thread backend/tests/unit/validations.test.ts Resolved
Comment thread backend/vitest.config.ts Resolved

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7ac348b and 09d4b0e.

📒 Files selected for processing (3)
  • backend/tests/unit/cloud-token.test.ts (1 hunks)
  • backend/tests/unit/validations.test.ts (1 hunks)
  • backend/vitest.config.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • backend/tests/unit/cloud-token.test.ts
  • backend/tests/unit/validations.test.ts
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions

Files:

  • backend/vitest.config.ts
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

React components and TypeScript types/interfaces must use PascalCase

Files:

  • backend/vitest.config.ts
**/[a-z][a-z0-9-]*.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Utility files should use kebab-case or camelCase (kebab-case validated here)

Files:

  • backend/vitest.config.ts
🧬 Code graph analysis (1)
backend/vitest.config.ts (1)
eslint.config.js (1)
  • __dirname (12-12)

Comment thread backend/vitest.config.ts Resolved

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 0

🧹 Nitpick comments (1)
backend/vitest.config.ts (1)

9-14: Critical issue resolved: alias configuration now correctly placed in resolve object.

The alias configuration has been correctly moved from inside the test object to a root-level resolve object, fixing the critical issue from previous reviews. The @ alias will now work properly for imports.

However, the indentation appears inconsistent—resolve (line 9) uses 4 spaces while test (line 15) uses 2 spaces. Both are properties of the config object and should have the same indentation per the coding guidelines.

Consider running Prettier to align the indentation:

 export default defineConfig({
-
-    resolve: {
-    alias: {
-      '@': path.resolve(__dirname, './src')
-    },
-
-  },
+  resolve: {
+    alias: {
+      '@': path.resolve(__dirname, './src')
+    },
+  },
   test: {

As per coding guidelines

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 09d4b0e and 35cadd2.

📒 Files selected for processing (1)
  • backend/vitest.config.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions

Files:

  • backend/vitest.config.ts
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

React components and TypeScript types/interfaces must use PascalCase

Files:

  • backend/vitest.config.ts
**/[a-z][a-z0-9-]*.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Utility files should use kebab-case or camelCase (kebab-case validated here)

Files:

  • backend/vitest.config.ts
🧬 Code graph analysis (1)
backend/vitest.config.ts (1)
eslint.config.js (1)
  • __dirname (12-12)
🔇 Additional comments (1)
backend/vitest.config.ts (1)

2-5: Critical issue resolved: __dirname now properly defined for ES modules.

The addition of fileURLToPath import and the __dirname definition correctly addresses the critical issue flagged in previous reviews. This matches the established pattern in eslint.config.js and prevents the ReferenceError that would occur when Vitest loads this configuration.

@Yasir761

Copy link
Copy Markdown
Contributor Author

@Leo-rq-yu, I have migrated to Vitest from Jest.

@Leo-rq-yu Leo-rq-yu left a comment

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.

Tested locally and working! @Yasir761 Thank you for the hard work!

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 3

🧹 Nitpick comments (1)
backend/tests/unit/cloud-token.test.ts (1)

24-32: Consider verifying mock calls to strengthen test coverage.

The test correctly validates the happy path result. You could optionally add assertions to verify that createRemoteJWKSet was called with the expected URL and that jwtVerify received the correct algorithms.

Example addition after line 31:

    expect(result.payload.user).toBe('testUser');
    // Optionally verify the mocks were called correctly:
    const { createRemoteJWKSet } = await import('jose');
    expect(createRemoteJWKSet).toHaveBeenCalledWith(
      new URL('https://mock-api.dev/.well-known/jwks.json')
    );
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 35cadd2 and 18d8fa8.

📒 Files selected for processing (7)
  • backend/src/utils/logger.ts (1 hunks)
  • backend/tests/unit/cloud-token.test.ts (1 hunks)
  • backend/tests/unit/constant.test.ts (1 hunks)
  • backend/tests/unit/helpers.test.ts (1 hunks)
  • backend/tests/unit/logger.test.ts (1 hunks)
  • backend/tests/unit/sql-parser.test.ts (1 hunks)
  • backend/vitest.config.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • backend/tests/unit/logger.test.ts
  • backend/tests/unit/sql-parser.test.ts
  • backend/src/utils/logger.ts
  • backend/tests/unit/constant.test.ts
  • backend/vitest.config.ts
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions

Files:

  • backend/tests/unit/cloud-token.test.ts
  • backend/tests/unit/helpers.test.ts
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

React components and TypeScript types/interfaces must use PascalCase

Files:

  • backend/tests/unit/cloud-token.test.ts
  • backend/tests/unit/helpers.test.ts
**/[a-z][a-z0-9-]*.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Utility files should use kebab-case or camelCase (kebab-case validated here)

Files:

  • backend/tests/unit/cloud-token.test.ts
  • backend/tests/unit/helpers.test.ts
🧬 Code graph analysis (2)
backend/tests/unit/cloud-token.test.ts (2)
backend/src/utils/cloud-token.ts (1)
  • verifyCloudToken (9-39)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/tests/unit/helpers.test.ts (1)
backend/src/utils/helpers.ts (1)
  • convertSqlTypeToColumnType (3-49)
🔇 Additional comments (4)
backend/tests/unit/helpers.test.ts (2)

1-3: LGTM!

The imports are correctly structured, using relative paths for internal modules and the configured alias for shared schemas.


15-62: Excellent test coverage and structure.

The test cases thoroughly verify all SQL type mappings, use forEach patterns effectively for similar cases, and include validation of the default behavior for unknown types. The test structure is clear and follows Vitest best practices.

backend/tests/unit/cloud-token.test.ts (2)

1-4: LGTM!

The imports are clean and follow TypeScript best practices—no file extensions, proper ES module syntax, and all necessary dependencies are included.


6-10: LGTM!

The jose module mocking is properly configured for Vitest. The setup allows flexible per-test configuration of jwtVerify while providing a simple mock for createRemoteJWKSet.

Comment thread backend/tests/unit/cloud-token.test.ts Resolved
Comment thread backend/tests/unit/cloud-token.test.ts Resolved
Comment thread backend/tests/unit/helpers.test.ts Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Unit Tests

2 participants