npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ivatra2/prisma-mock

v0.10.2

Published

Mock prisma for unit testing database

Downloads

5

Readme

Prisma Mock

This is a mock of the Prisma API intended for unit testing. All the data is stored in memory.

The library jest-mock-extended is used, which means that if functionality you need is not implemented yet, you can mock it yourself.

Usage

Simple example how to create a prisma mock instance:

import createPrismaMock from "prisma-mock"

let client

beforeEach(() => {
  client = createPrismaMock()
})

An example how to mock a global prisma instance, as the default export in a "db" directory (like blitzjs):

import createPrismaMock from "prisma-mock"
import { mockDeep, mockReset } from "jest-mock-extended"

jest.mock("db", () => ({
  __esModule: true,
  ...jest.requireActual("db"),
  default: mockDeep(),
}))

import db, { Prisma } from "db"

beforeEach(() => {
  mockReset(db)
  createPrismaMock({}, Prisma.dmmf.datamodel)
})

API

createPrismaMock(
  data: PrismaMockData<P> = {},
  datamodel?: Prisma.DMMF.Datamodel,
  client = mockDeep<P>(),
  options: {
    caseInsensitive?: boolean
  } = {}
): Promise<P>

Arg: data

You can optionally start up a pre-filled db, by passing in an object containing keys for tables, and values as arrays of objects (though using create is preferred). Example:

createPrismaMock({
  user: [
    {
      id: 1,
      name: "John Doe",
      accountId: 1,
    },
  ],
  account: [
    {
      id: 1,
      name: "Company",
    },
  ],
})

Arg: datamodel

The datamodel of the prisma client, value of Prisma.dmmf.datamodel.

Arg: client

A jest-mock-extended instance. If not provided, a new instance is created.

Arg: caseInsensitive

If true, all string comparisons are case insensitive.

Supported features

Most common cases are covered, but not everything. Here is a rough list of the supported features:

Model queries

  • findUnique,
  • findUniqueOrThrow,
  • findMany,
  • findFirst,
  • findFirstOrThrow,
  • create,
  • createMany
  • delete,
  • update,
  • deleteMany,
  • updateMany
  • upsert
  • count
  • TODO: aggregate
  • TODO: groupBy

Model query options

  • distinct
  • include
  • where
  • select
  • orderBy
  • select: _count

Nested queries

  • create
  • createMany
  • update
  • updateMany
  • delete
  • deleteMany
  • connect
  • disconnect
  • set
  • upsert
  • TODO: connectOrCreate

Filter conditions and operators

  • equals
  • gt
  • gte
  • lt
  • lte
  • not
  • in
  • notIn
  • contains
  • startWith
  • endsWith
  • AND
  • OR
  • NOT
  • mode
  • TODO: search

Relation filters

  • some
  • every
  • none
  • TODO: is

Scalar list methods

TODO (set, push)

Scalar list filters

TODO (has, hasEvery, hasSome, isEmpty, equals)

Atomic number operations

  • increment
  • decrement
  • multiply
  • divide
  • set

JSON filters

  • path
  • string_contains
  • string_starts_with
  • string_ends_with
  • array_contains
  • array_starts_with
  • array_ends_with

Attributes

  • @@id
  • @default
  • @unique
  • @@unique (TODO: no error if duplicate)
  • @relation
  • @updatedAt: Partially supported, value is set at creation (TODO: update value on update)

Attribute functions

  • autoincrement()
  • TODO: auto()
  • cuid()
  • uuid()
  • now()
  • TODO: dbgenerated()

Referential actions

  • onDelete (SetNull, Cascade)
  • TODO: onDelete: Restrict, NoAction, SetDefault
  • TODO: onUpdate

Prisma Client methods

  • $transaction
  • $transaction (interactive)
  • TODO: $transaction (isolation)

Contribution

Requirements

Create a .env-cmdrc file in the root of your project with the following content:

{
  "postgres": {
    "PROVIDER": "postgresql",
    "DATABASE_URL": "postgresql://postgres:postgres@localhost:5432/postgres?schema=public"
  }
}

Writing Tests

Create your tests in the __tests__ directory. You can use snapshot testing with either expect(res).toMatchSnapshot() or expect(res).toMatchInlineSnapshot(). This captures the result of your tests in a snapshot, which you can use to compare agains prisma-mock results.

Note: If you choose to use snapshot testing, make shore to first run your tests against the real database to create a snapshot of the expected result.

Running Tests

To run tests against a postgres database, run the following command:

yarn run test:postgres

To run tests against prisma-mock (in-memory database), run:

yarn test