Repository navigation
test: add unit test for utilities - #441
Conversation
WalkthroughRemoved Changes
Sequence Diagram(s)No sequence diagram — changes don't modify runtime control flow. Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (5)
backend/src/utils/logger.ts (1)
3-3: Minor: Fix double space beforelogger.The named export is a good addition for import flexibility, but there's an extra space between
constandlogger.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
pathsconfiguration (lines 30-33) duplicates logic frommoduleNameMapper(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:
Enable roots option: If your tests are organized under
tests/unit, uncomment line 39 to scope test discovery.Add test file patterns: Explicitly specify test file patterns for clarity:
testMatch: ['**/__tests__/**/*.(test|spec).ts', '**/?(*.)+(spec|test).ts'],
- Configure coverage collection: Add coverage configuration if not already in package.json:
collectCoverageFrom: [ 'src/**/*.ts', '!src/**/*.d.ts', '!src/**/__tests__/**', ],
- 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
⛔ Files ignored due to path filters (1)
package-lock.jsonis 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.tsbackend/tests/unit/cloud-token.test.tsbackend/tests/unit/uuid.test.tsbackend/src/utils/cloud-token.tsbackend/tests/unit/helpers.test.tsbackend/tests/unit/constant.test.tsbackend/tests/unit/enviroment.test.tsbackend/src/utils/validations.tsbackend/tests/unit/validations.test.tsbackend/src/api/middleware/error.tsbackend/tests/unit/sql-parser.test.tsbackend/tests/unit/logger.test.tsbackend/tests/unit/response.test.tsbackend/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.tsbackend/src/utils/cloud-token.tsbackend/src/utils/validations.tsbackend/src/api/middleware/error.tsbackend/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.tsbackend/tests/unit/cloud-token.test.tsbackend/tests/unit/uuid.test.tsbackend/src/utils/cloud-token.tsbackend/tests/unit/helpers.test.tsbackend/tests/unit/constant.test.tsbackend/tests/unit/enviroment.test.tsbackend/src/utils/validations.tsbackend/tests/unit/validations.test.tsbackend/src/api/middleware/error.tsbackend/tests/unit/sql-parser.test.tsbackend/tests/unit/logger.test.tsbackend/tests/unit/response.test.tsbackend/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.tsbackend/tests/unit/cloud-token.test.tsbackend/tests/unit/uuid.test.tsbackend/src/utils/cloud-token.tsbackend/tests/unit/helpers.test.tsbackend/tests/unit/constant.test.tsbackend/tests/unit/enviroment.test.tsbackend/src/utils/validations.tsbackend/tests/unit/validations.test.tsbackend/src/api/middleware/error.tsbackend/tests/unit/sql-parser.test.tsbackend/tests/unit/logger.test.tsbackend/tests/unit/response.test.tsbackend/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 declaresjest ^29 || ^30as 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
generateUUIDutility:
- 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)andtoContain, suggesting the parser may not be splitting statements as expected.Based on the implementation in
backend/src/utils/sql-parser.ts, the parser usessplitSqlQueryand filters out comment-only statements. The test expectations should match this behavior. Verify whether:
- Comments within statements are preserved (expected)
- Multiple statements are properly split (expected based on line 5-17)
- 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
joselibrary and tests both successful token verification and error cases. The tests correctly verify that:
- Valid tokens return the expected payload and projectId
- 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 configurationThe mapping for
@insforge/shared-schemascorrectly points toshared-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).
There was a problem hiding this comment.
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
📒 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.
|
@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! |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
backend/tests/unit/environment.test.ts (2)
11-17: Consider usingafterEachinstead ofafterAllfor better test isolation.While the current approach works, using
afterEachto 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
📒 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
isOAuthSharedKeysAvailabledelegates toisCloudEnvironmentfor both true and false cases.
37-57: LGTM!Both
isDevelopmentandisProductiontests comprehensively cover all branches:
- Explicit 'development' and 'production' values
- Opposite environment values
- Undefined/missing
NODE_ENVedge caseThe test logic correctly matches the source implementations.
|
@Leo-rq-yu, thanks for catching that! 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 |
|
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! |
There was a problem hiding this comment.
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 setsLOG_LEVELto a specific value (e.g., 'debug') and verifies it's used, and another that explicitly unsetsLOG_LEVELand 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 whereAWS_INSTANCE_PROFILE_NAMEis an empty string or contains only whitespace. Both should returnfalse.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 usingvi.mocked(jwtVerify)if types are set up correctly, or simply cast toanyfor 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
⛔ Files ignored due to path filters (1)
package-lock.jsonis 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.tsbackend/tests/unit/cloud-token.test.tsbackend/tests/unit/logger.test.tsbackend/tests/unit/validations.test.tsbackend/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.tsbackend/tests/unit/cloud-token.test.tsbackend/tests/unit/logger.test.tsbackend/tests/unit/validations.test.tsbackend/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.tsbackend/tests/unit/cloud-token.test.tsbackend/tests/unit/logger.test.tsbackend/tests/unit/validations.test.tsbackend/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
isOAuthSharedKeysAvailablemirrorsisCloudEnvironmentbehavior. 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_ENVis unset.
49-58: LGTM! Complete validation of isProduction logic.The tests correctly validate the implementation: returns
trueonly for 'production', andfalsefor all other cases including whenNODE_ENVis unset.backend/tests/unit/logger.test.ts (2)
1-2: LGTM! Imports are correct.The named
loggerexport 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.
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 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)
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
backend/vitest.config.ts (1)
9-14: Critical issue resolved: alias configuration now correctly placed inresolveobject.The alias configuration has been correctly moved from inside the
testobject to a root-levelresolveobject, 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 whiletest(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
📒 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:__dirnamenow properly defined for ES modules.The addition of
fileURLToPathimport and the__dirnamedefinition correctly addresses the critical issue flagged in previous reviews. This matches the established pattern ineslint.config.jsand prevents theReferenceErrorthat would occur when Vitest loads this configuration.
|
@Leo-rq-yu, I have migrated to Vitest from Jest. |
There was a problem hiding this comment.
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
createRemoteJWKSetwas called with the expected URL and thatjwtVerifyreceived 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
📒 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.tsbackend/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.tsbackend/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.tsbackend/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.
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
Chores
Refactor