How to easily setup mongodb for cypress
Tests should be isolated with each other. Today let’s see an easy way to setup and teardown your MongoDB database before each cypress run. The concept should be applicaple to other senario other than cypress, and the code for setup the MongoDB should be able to adapt to other cases as well.
1. Dump your data with MongoDB Compass
If you haven’t download, download it here. It’s a GUI for CRUD your MongoDB collections, directly from official MongoDB team.
After selecting the collection on the left hand side, you will see a Export icon with the label “Export Collection”
Click that to export your collection, save as JSON.
2. Prepare for loading that data in your frontend app.
- Install
mongo
as dev-dependencies:npm i mongo -D
- add a folder named
database
in yourcypress
folder - copy the previous JSON files into this newly created folder
- add a file named
seedMongo.js
in this folder with the following code
1 | const MongoClient = require("`mongodb`").MongoClient; |
Seems to be a lot going on but actually quite simple, let’s decipher it. In short, any lines below async function dropAndSeed
is generic. You only need to worry about the part above it.
So, you basically,
- import the JSON data like
const apartments = require("./apartments.json");
- create the database name like
const DB = "my-e2e";
- create a pure object
dataToSeed
with all the JSON data, the key would be the collection name. - Change the logic in
oidToObjectId()
to suit your needs. The reason we need this is, the data dumped fromMongoDB Compass
, the id field is like this:"_id": { "$oid": "60e6c7ae0973e96ac3ebaeb8"},
, theoidToObjectId
will convert it to"_id": ObjectId("60e6c7ae0973e96ac3ebaeb8")
, that’s all.
3. add a command in your package.json
1 | "scripts":{ |
4. Adding this step in your cypress test
1 | describe('The Homepage', () => { |
5. End
That’s it. Now the database will be teardown and re-seed before each run.