Prisma Mock
prisma-mock is an in-memory mocking library designed for unit testing applications that interact with Prisma ORM. It fully simulates the Prisma API, allowing developers to execute database-dependent unit tests rapidly without requiring an actual database connection or external dependencies. The current stable version is 1.1.0, with an active release cadence involving frequent patch and minor updates to support new Prisma versions and features. A key differentiator is its in-memory data storage, which ensures fast and reliable test execution. It offers optional integration with `jest-mock-extended` or `vitest-mock-extended` for enhanced mocking capabilities and provides dedicated entry points (`prisma-mock` vs. `prisma-mock/client`) to accommodate different Prisma client versions. The library also supports initializing the mock client with pre-filled data and includes methods like `$clear()` and `$setInternalState()` for robust state management across tests, making it a comprehensive tool for isolating database logic during testing.
Common errors
-
Error: Cannot read properties of undefined (reading 'datamodel')
cause `createPrismaMock` was called without the `datamodel` option when using `prisma-mock/client` for Prisma 7+, or the `dmmf` object was incorrectly imported or passed.fixFor Prisma 7+, ensure you have configured and run the DMMF generator in your `schema.prisma`. Then, import `* as dmmf from './generated/dmmf'` (or similar path) and pass it as `createPrismaMock(Prisma, { datamodel: dmmf })`. -
TypeError: createPrismaMock is not a function
cause This typically occurs when attempting to `require` the `prisma-mock` or `prisma-mock/client` package in an ESM context, or due to an incorrect import path.fixFor ESM projects, use `import createPrismaMock from 'prisma-mock'` or `import createPrismaMock from 'prisma-mock/client'`. If in a CommonJS environment, ensure your project setup correctly handles ESM imports, or verify the package's export map configuration. -
ReferenceError: Prisma is not defined
cause When using `prisma-mock/client` (required for Prisma 7+), the `Prisma` namespace was not imported or passed correctly as the first argument to `createPrismaMock`.fixEnsure you are importing `Prisma` from your generated Prisma client (e.g., `import { Prisma } from "./generated/client";`) and passing it as the first argument to `createPrismaMock`.
Warnings
- breaking The `v1.0.0` release introduced significant breaking changes to the API interface, requiring a review of how `createPrismaMock` is called. It also enabled indexing by default for performance improvements, which might subtly alter behavior if previous versions relied on unindexed behavior.
- deprecated The `prisma-mock/legacy` export is deprecated. While currently maintained for backward compatibility, new projects and refactors should migrate to the recommended `prisma-mock` (for Prisma 6 and below) or `prisma-mock/client` (for Prisma 7+) entry points.
- gotcha For Prisma v7 and above, `prisma-mock/client` must be used. This entry point explicitly requires the `Prisma` namespace and a `dmmf` object (generated by a DMMF generator) to be passed during initialization. Failure to provide these or properly configure the DMMF generator will lead to runtime errors.
- gotcha When mocking a global Prisma client instance (e.g., a default export in a `db` module), it's crucial to correctly set up your mocking library (e.g., `jest.mock`) and ensure `mockDeep` and `mockReset` are used with `createPrismaMock({ mockClient: db })`. Incorrect setup can lead to state leakage between tests or unexpected behavior.
Install
-
npm install prisma-mock -
yarn add prisma-mock -
pnpm add prisma-mock
Imports
- createPrismaMock
const createPrismaMock = require("prisma-mock");import createPrismaMock from "prisma-mock";
- createPrismaMock
const createPrismaMock = require("prisma-mock/client");import createPrismaMock from "prisma-mock/client";
- Prisma
import { Prisma } from "./generated/client"; - dmmf
import * as dmmf from "./generated/dmmf";
Quickstart
import createPrismaMock from "prisma-mock/client";
import { Prisma } from "./generated/client"; // Adjust path based on your Prisma client generation
import * as dmmf from "./generated/dmmf"; // Ensure DMMF generator is configured and run
let client: ReturnType<typeof createPrismaMock>;
beforeEach(() => {
// Initialize the mock client before each test
client = createPrismaMock(Prisma, {
datamodel: dmmf,
// Optionally start with some initial data
data: {
user: [
{ id: 1, name: 'Initial User', email: 'initial@example.com' }
]
}
});
// Clear any state from previous tests
client.$clear();
});
describe('User operations', () => {
it('should create a new user', async () => {
const newUser = await client.user.create({
data: {
id: 2,
name: 'Alice Smith',
email: 'alice@example.com',
},
});
expect(newUser).toEqual({ id: 2, name: 'Alice Smith', email: 'alice@example.com' });
const userCount = await client.user.count();
expect(userCount).toBe(2); // Includes initial user
});
it('should find a user by ID', async () => {
// Create a user specifically for this test if not pre-seeded
await client.user.create({ data: { id: 3, name: 'Bob Johnson', email: 'bob@example.com' } });
const foundUser = await client.user.findUnique({ where: { id: 3 } });
expect(foundUser?.name).toBe('Bob Johnson');
});
it('should update an existing user', async () => {
const updatedUser = await client.user.update({
where: { id: 1 },
data: { name: 'Updated Initial User' },
});
expect(updatedUser?.name).toBe('Updated Initial User');
});
});