how to do unit tests?

I can't find any reliable resource on unit test where we mock the drizzle instance. I don't want to set up a real db connection with either a docker container that I would run alongside my tests or with testcontainers. because of the drizzle chain methods api it's not that convenient to use for example vitest vi.spyOn method I tried to create a method that has a similar api to spyOn but works with methods like so:
mockChain(db, 'select().from().limit()').mockResolvedValue([{}])
mockChain(db, 'select().from().limit()').mockResolvedValue([{}])
but I was wondering how people using drizzle where mocking this layer it seems prisma has documentation on how to deal with it https://www.prisma.io/docs/orm/prisma-client/testing/unit-testing
Unit testing with Prisma ORM | Prisma Documentation
Learn how to setup and run unit tests with Prisma Client
2 Replies
KirbyTwister
KirbyTwister2mo ago
You could try this but it's not really documented in-depth https://orm.drizzle.team/docs/goodies#mock-driver
Drizzle ORM - Goodies
Drizzle ORM is a lightweight and performant TypeScript ORM with developer experience in mind.
bebenzer
bebenzerOP2mo ago
yea I used it in another project, though in my experience it didnt solve the DX while writing tests where I needed to mock the db:
const db = drizzle.mock({ schema })

const returningMock = vi.fn()
const valuesMock = vi.fn().mockReturnValue({ returning: returningMock })
const insertSpy = vi.spyOn(db, 'insert').mockReturnValue(...)
const repo = new CustomerSchedulersRepository(db)
repo.insert(...)
const db = drizzle.mock({ schema })

const returningMock = vi.fn()
const valuesMock = vi.fn().mockReturnValue({ returning: returningMock })
const insertSpy = vi.spyOn(db, 'insert').mockReturnValue(...)
const repo = new CustomerSchedulersRepository(db)
repo.insert(...)
if I have chained method I would still need to mock each submethod in this example it would be db.insert().values().returning() that needs to be mocked, so I have 3 vi.fn it was useful as the db wont try to create a connection to the db, and the object returned by drizzle.mock is typed like the real db instance I would use

Did you find this page helpful?