Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot use Factory in beforeAll() or afterAll() while running test cases using jest-prisma #438

Open
Velogan-Boy opened this issue Feb 14, 2025 · 0 comments

Comments

@Velogan-Boy
Copy link

Bug Report: Factory Usage in Jest Hooks with jest-prisma

Description

Using Factory utilities in beforeAll()/afterAll() Jest hooks with jest-prisma results in transaction errors. The package's transaction wrapper is only active during test cases (it blocks) or beforeEach/afterEach hooks, causing Factory operations in beforeAll/afterAll to fail.


Error Message

Error: jestPrisma.client should be used in test or beforeEach functions because transaction has not yet started.

Reproduction Steps

  1. Create a test suite with jest-prisma.

  2. Use Factory in a beforeAll hook:

    import { Factory } from '@/tests/factories';  
    
    describe('Test Suite', () => {  
      beforeAll(async () => {  
        // ❌ Fails  
        await Factory.User.create();  
      });  
    
      it('test case', () => { /* ... */ });  
    });  
  3. Run tests and observe the transaction error.


Expected Behavior

Factory utilities should work in all Jest lifecycle hooks when using jest-prisma.

Actual Behavior

Factory usage in beforeAll/afterAll throws transaction errors.


Workaround

Use jestPrisma.originalClient directly for setup/teardown in hooks:

beforeAll(async () => {  
  // ✅ Works with raw queries  
  await jestPrisma.originalClient.user.create({   
    data: {   
      email: '[email protected]',  
      // ... other required fields  
    }   
  });  
});  

Suggested Fixes

  • Allow Factory patterns to use originalClient internally for hooks.
  • Document this limitation and provide migration examples.

Code Example (Failure vs. Success)

❌ Fails in beforeAll/afterAll

beforeAll(async () => {  
  const user = await Factory.User.create(); // ❌ Transaction error  
});  

✅ Works in beforeEach/it

beforeEach(async () => {  
  const user = await Factory.User.create(); // ✅ Works  
});  

Impact

Forces developers to:

  • Mix Factory patterns with raw queries
  • Maintain inconsistent test setup patterns
  • Increase technical debt in test suites

Priority: High

Severity: Major (reduces code maintainability)

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

No branches or pull requests

1 participant