Skip to content

Test/setup#4

Merged
i-am-that-guy merged 2 commits intomainfrom
test/setup
Jul 18, 2025
Merged

Test/setup#4
i-am-that-guy merged 2 commits intomainfrom
test/setup

Conversation

@Harish-Naruto
Copy link
Copy Markdown
Member

@Harish-Naruto Harish-Naruto commented Jul 18, 2025

added test setup

Summary by CodeRabbit

  • Chores

    • Replaced JavaScript Jest configuration with a TypeScript version for improved type safety and clarity.
    • Updated package dependencies: added "jest-mock-extended" and removed "@types/bun".
    • Introduced a Jest mock setup for the PrismaClient to streamline database testing.
  • Tests

    • Improved unit tests by replacing a trivial test with a comprehensive test for project creation, utilizing mocked database interactions.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jul 18, 2025

Walkthrough

The changes replace the Jest configuration from a JavaScript to a TypeScript file, update package dependencies, and introduce a singleton mock setup for PrismaClient using jest-mock-extended. The test suite is updated to include a unit test for the createProject service, employing the new Prisma mock for database interaction.

Changes

File(s) Change Summary
jest.config.js Removed JavaScript-based Jest configuration file.
jest.config.ts Added TypeScript-based Jest configuration with TypeScript preset and test pattern updates.
package.json Added jest-mock-extended to devDependencies; removed @types/bun from dependencies.
singleton.ts Introduced singleton Jest mock for PrismaClient with beforeEach reset and deep mock proxy.
tests/Sample.test.ts Replaced trivial test with a unit test for createProject using Prisma mock.

Sequence Diagram(s)

sequenceDiagram
    participant TestRunner as Jest Test Runner
    participant Singleton as singleton.ts (Prisma Mock)
    participant Service as createProject Service
    participant Prisma as PrismaClient (Mocked)

    TestRunner->>Singleton: Import prismaMock
    TestRunner->>Service: Call createProject(input)
    Service->>Prisma: project.create(input)
    Prisma-->>Service: Return mocked Project object
    Service-->>TestRunner: Return Project object
Loading

Poem

In the warren where tests now hop,
A Prisma mock takes center spot.
TypeScript config, neat and bright,
Guides each bunny through the night.
With jest-mock-extended, our tests are strong—
The code hops forward, singing its song!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-07-18T17_41_39_746Z-debug-0.log

✨ Finishing Touches
  • 📝 Docstrings were successfully generated. (🔄 Check again to generate docstrings again)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
jest.config.ts (1)

2-7: LGTM! Clean TypeScript Jest configuration.

The Jest configuration is appropriate for TypeScript testing with proper preset and environment settings.

Consider adding these optional configurations for better test experience:

export default {
  preset: 'ts-jest',
  testEnvironment: 'node',
  moduleFileExtensions: ['ts', 'js', 'json'],
  testMatch: ['**/tests/**/*.test.ts'],
+ setupFilesAfterEnv: ['<rootDir>/singleton.ts'],
+ collectCoverageFrom: [
+   'src/**/*.ts',
+   '!src/**/*.d.ts',
+ ],
}
tests/Sample.test.ts (1)

6-35: Excellent test structure with proper mocking and assertions.

The test follows best practices with:

  • Clear test data setup
  • Proper mock configuration
  • Comprehensive assertions for both method calls and return values
  • Good use of async/await

Consider adding a beforeEach hook to reset mocks for this specific test:

describe('createProject', () => {
+ beforeEach(() => {
+   jest.clearAllMocks()
+ })
+
  it('should create a new project and return it', async () => {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3e8c0d7 and 066f223.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (5)
  • jest.config.js (0 hunks)
  • jest.config.ts (1 hunks)
  • package.json (1 hunks)
  • singleton.ts (1 hunks)
  • tests/Sample.test.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • jest.config.js
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/Sample.test.ts (1)
singleton.ts (1)
  • prismaMock (17-17)
🔇 Additional comments (2)
package.json (1)

33-33: LGTM! Appropriate dependency addition for Jest mocking.

The addition of jest-mock-extended as a devDependency is correctly placed and supports the new mocking capabilities introduced in the test setup.

singleton.ts (1)

6-12: Mock initialization and import path confirmed; verify hook execution

The src/db/client.ts file exports prisma as expected, and mock is declared (line 4) before the jest.mock factory (line 6), so assignment is safe. The beforeEach reset (lines 19–21) sits at module scope—please confirm that singleton.ts is loaded via Jest’s setupFilesAfterEnv (or explicitly imported in your tests) so the reset runs before each test.

• File: singleton.ts
– Lines 4 & 6: let mock declared prior to jest.mock
– Lines 19–21: module-scoped beforeEach hook

• Action: Ensure your Jest config (e.g. setupFilesAfterEnv) includes this file or that it’s imported in every test suite.

Comment on lines +19 to +21
beforeEach(() => {
mockReset(prismaMock)
})
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot Jul 18, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Move beforeEach hook to test files for better isolation.

The module-level beforeEach hook may not work as expected. Consider moving this to individual test files or using a Jest setup file configuration.

-beforeEach(() => {
-  mockReset(prismaMock)
-})

Instead, add this to your test files or configure it in Jest setupFilesAfterEnv.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
beforeEach(() => {
mockReset(prismaMock)
})
🤖 Prompt for AI Agents
In singleton.ts around lines 19 to 21, the beforeEach hook that resets
prismaMock should be removed from this module-level file and instead placed
inside each individual test file that requires it, or alternatively configured
globally in a Jest setup file using setupFilesAfterEnv. This change ensures
better test isolation and proper hook execution.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

why would it be better to have it in each test file? and what's the issue with the module level before each

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.

@i-am-that-guy Great question! Let me explain the technical issues with module-level beforeEach hooks:

Problems with Module-Level beforeEach

  1. Global Scope Pollution: When you define beforeEach at the module level (outside any describe block), Jest registers it globally. This means it runs before every single test in your entire test suite, even tests that don't use Prisma or this mock.

  2. Performance Overhead: Tests that don't need the prismaMock will still execute mockReset(prismaMock), adding unnecessary overhead to your test runs.

  3. Unexpected Behavior: The hook executes based on module loading order, which can be unpredictable. If this module is imported by multiple test files, the hook might not behave as expected.

  4. Test Isolation Issues: While you want mock resets for isolation, having it run globally can interfere with other tests that might have their own mock management strategies.

Better Alternatives

Option 1: In individual test files

// tests/project.test.ts
import { prismaMock } from '../singleton'

describe('Project tests', () => {
  beforeEach(() => {
    mockReset(prismaMock)
  })
  
  // your tests here
})

Option 2: Jest setup file (recommended for global mock resets)

// jest.setup.ts
import { mockReset } from 'jest-mock-extended'
import { prismaMock } from './singleton'

beforeEach(() => {
  mockReset(prismaMock)
})

Then configure it in jest.config.ts:

export default {
  // ... other config
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
}

The setup file approach is cleaner if you want global mock resets, while individual test file hooks give you more granular control.

Comment on lines +2 to +4
import { prismaMock } from '../singleton';
import { Project } from '../src/generated/prisma';
import { createProject } from '../src/services/project.service';
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.

💡 Verification agent

🧩 Analysis chain

Verify import paths and add mock reset to test setup.

The test structure is excellent, but please verify these import paths exist:

  • ../singleton (should exist based on the new file)
  • ../src/generated/prisma (Prisma generated types)
  • ../src/services/project.service (the service being tested)

🏁 Script executed:

#!/bin/bash
# Verify the existence of imported files and their exports
echo "Checking singleton file:"
ls -la singleton.ts

echo -e "\nChecking Prisma generated types:"
fd -t f "index" src/generated/prisma/ --exec head -20 {}

echo -e "\nChecking project service:"
fd -t f "project.service" src/services/ --exec head -10 {}

Length of output: 718


I need a closer look at your Prisma mock setup and actual type locations to confirm import paths and recommended mock reset handling.

Let's gather:

#!/bin/bash
# Inspect mock singleton implementation
head -100 singleton.ts

# List all 'generated' directories
fd -t d generated

# Find any exported 'Project' type in src
rg "export.*Project" -n src || true

# Check for '@prisma/client' imports to locate type source
rg "@prisma/client" -n src || true

Fix import paths and add mock reset in tests

Your test file references non-existent modules and misses the mock reset hook. Please update as follows:

• Replace the invalid Prisma types import. There is no src/generated/prisma directory—import Project straight from @prisma/client:

- import { Project } from '../src/generated/prisma';
+ import { Project } from '@prisma/client';

• Ensure createProject is actually exported by your service. The current src/services/project.service.ts only exports getProjects and getProjectById. Either:

  • Export or implement createProject there, or
  • Point your import to the correct file where createProject lives.

• Reset your mock between tests to avoid state leakage. At the top of tests/Sample.test.ts, add:

beforeEach(() => {
  prismaMock.$reset();
});

With these fixes in place, your imports will resolve correctly and each test will start with a clean mock.

🤖 Prompt for AI Agents
In tests/Sample.test.ts around lines 2 to 4, fix the import paths by replacing
the import of Project from '../src/generated/prisma' with an import from
'@prisma/client' since the former path does not exist. Verify that createProject
is correctly exported from the service file; if not, either export or implement
createProject in src/services/project.service.ts or update the import to the
correct file where createProject is defined. Additionally, add a beforeEach hook
at the top of the test file to call prismaMock.$reset() to reset the mock state
before each test and prevent state leakage.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jul 18, 2025

Caution

No docstrings were generated.

Copy link
Copy Markdown
Member

@i-am-that-guy i-am-that-guy left a comment

Choose a reason for hiding this comment

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

good work

@i-am-that-guy i-am-that-guy merged commit 65058fc into main Jul 18, 2025
2 checks passed
@Harish-Naruto Harish-Naruto deleted the test/setup branch July 21, 2025 15:47
@coderabbitai coderabbitai bot mentioned this pull request Jul 21, 2025
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.

2 participants