I need to query mongo inside my Cypress tests to basically see if my POST is updating some fields, but I don't see a npm package for it like there is for sql server. Googling it I only see documentation and examples on how to seed the db. Any thoughts, comments? Thank you
CodePudding user response:
Take a look at this post: https://glebbahmutov.com/blog/testing-mongo-with-cypress/
The gist of it:
-- plugins/index.js
/// <reference types="cypress" />
const { connect } = require('../../db')
module.exports = async (on, config) => {
const db = await connect()
const pizzas = db.collection('pizzas')
on('task', {
async clearPizzas() {
console.log('clear pizzas')
await pizzas.remove({})
return null
},
})
}
-- db.js
const { MongoClient } = require('mongodb')
const uri = process.env.MONGO_URI
if (!uri) {
throw new Error('Missing MONGO_URI')
}
const client = new MongoClient(uri)
async function connect() {
// Connect the client to the server
await client.connect()
return client.db('foods')
}
async function disconnect() {
// Ensures that the client will close when you finish/error
await client.close()
}
module.exports = { connect, disconnect }
Change the line await pizzas.remove({})
to whatever query you want to run, I'll assume you know how to get the result of the query and assert it.