vitest-environment-mongodb
v2.0.0
Published
Sets up a MongoDB memory-server environment for testing with Vitest.
Readme
vitest-environment-mongodb
Setup a MongoDB environment for Vitest tests using mongodb-memory-server.
This package provides a Vitest environment that uses mongodb-memory-server to create an in-memory MongoDB instance for testing purposes. It is designed to be used with Vitest, a Vite-native test framework.
It will spin up a memory server instance, and set the connection string on
process.env.MONGO_CONNECTION_STRING by default, or value you can configure
with mongoUrlEnvName option.
Installation
Use your favorite package manager to install the package:
npm install --save-dev vitest-environment-mongodbor
yarn add --dev vitest-environment-mongodbor
pnpm add --save-dev vitest-environment-mongodbUsage
Once installed, you can use the environment in your Vitest configuration per the documentation.
Use in Vitest config
import { defineConfig } from "vitest/config"
export default defineConfig({
test: {
environment: "mongodb",
environmentOptions: {
mongoUrlEnvName: "MONGO_CONNECTION_STRING", // optional, default is MONGO_CONNECTION_STRING
replicaSet: false, // optional, default is false
serverOptions: MongoMemoryServerOpts | MongoMemoryReplSetOpts, //optional, server options for the chosen server type
},
},
})Use control comment in a test file
// @vitest-environment mongodb
import { expect, test } from "vitest"
import { UserCollection } from "./models/UserCollection"
test("should create a user", async () => {
const { insertedId } = await UserCollection.insertOne({ name: "John Doe" })
const user = await UserCollection.findOne({ _id: insertedId })
expect(user).toBeDefined()
expect(user).toHaveProperty("name")
expect(user).toHaveProperty("_id")
expect(user.name).toBe("John Doe")
})Options
mongoUrlEnvName(string): The name of the environment variable that will contain the MongoDB connection string. Default isMONGO_CONNECTION_STRING.replicaSet(boolean): Whether to use a replica set. Default isfalse.serverOptions(MongoMemoryServerOpts | MongoMemoryReplSetOpts): An options object that will passed through to themongodb-memory-serverpackage. Be sure to use the options for the server type you are using, eitherMongoMemoryReplSetOptswhenreplicaSet=trueorMongoMemoryServerOptsforreplicaSet=false.
