Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

cypress-mongodb

Package Overview
Dependencies
Maintainers
1
Versions
36
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cypress-mongodb

Cypress MongoDB plugin

  • 5.4.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
12K
increased by30.17%
Maintainers
1
Weekly downloads
 
Created
Source

Introduction

Plugin that allows interaction with MongoDB server using Cypress commands.

Installation

run npm install cypress-mongodb
configure (see below)
profit

Supported and tested system versions

Versions
MongoDB4.4, 5.0, 6.0
Node16.20, 18.16, 19.9
MongoDB Node.js Driver4.10.0

known issues

If you use mongodb dependency in your project, it hast to be version <=4.10.0, otherwise you'll get a Webpack compilation error

Environment setup

Add the following env properties in your cypress.config.js file:

{
    module.exports = defineConfig({
        "env": {
            "mongodb": {
                "uri": "mongodb://localhost:27017",
                "database": "database_name",
                "collection": "collection_name"
            }
        }
    });
}

Note: only mongodb.uri is mandatory, you can always override/set database and collection names in each cypress mongodb command using options. You can set both local and remote urls.

Plugin configuration - JavaScript

In your cypress.config.js add the following:

const mongo = require('cypress-mongodb');

module.exports = defineConfig({
    e2e: {
        setupNodeEvents(on, config) {
            mongo.configurePlugin(on);
        }
    }
});

In your cypress/support/e2e.js add the following:

const mongo = require('cypress-mongodb');
mongo.addCommands();

Plugin configuration - TypeScript

In your cypress.config.ts add the following:

import {defineConfig} from 'cypress'
import {configurePlugin} from 'cypress-mongodb';

/**
 * @type {Cypress.PluginConfig}
 */
export default defineConfig({
    e2e: {
        setupNodeEvents(on) {
            configurePlugin(on);
        }
    }
});

In your cypress/support/e2e.ts add the following:

import {addCommands} from "cypress-mongodb";

addCommands();

Documentation

Collection commands

> syntax

cy.createCollection(collectionName);
cy.createCollection(collectionName, options);

cy.dropCollection(collectionName);
cy.dropCollection(collectionName, options);

> arguments

ArgumentsTypeDescription
collectionNameString (required)Name of the collection to create/drop
optionsObject (optional)Provide additional options (see below)

> options

OptionsDefaultDescription
databaseValue specified in the mongodb environment variableDatabase on top of which the command will be executed
failSilentlyfalseControl if the command will fail or if the collection is not found

> examples

cy.createCollection('someCollection'); // collection with name `someCollection` will be created

cy.createCollection('someOtherCollection', { database: 'someDatabase', failSilently: 'true' }).then(result => {
    cy.log(result); // Will return 'Collection created' or the error object if collection already exists. Will not fail the test 
});

cy.dropCollection('someCollection'); // collection will be droped

cy.dropCollection('nonexistentCollection', { database: 'someDatabase', failSilently: 'true' }).then(result => {
    cy.log(result); // Will return 'Collection dropped' or the error object if collection doesn’t exist. Will not fail the test
});

Insert commands

> syntax

cy.insertOne(document);
cy.insertOne(document, options);

cy.insertMany(documents);
cy.insertMany(documents, options);

> arguments

ArgumentsTypeDescription
documentObject (required)A Document object that will be inserted
documentsObject[] (required)An array of Document objects that will be inserted
optionsObject (optional)Provide additional options (see below)

> options

OptionsDefaultDescription
collectionValue specified in the mongodb environment variableDatabase on top of which the command will be executed
databaseValue specified in the mongodb environment variableCollection on top of which the command will be executed

> examples

cy.insertOne({document: 1}; // will insert the provided document in mongodb

cy.insertOne({document: 1}, {collection: 'someCollection', database: 'someDatabase'}).then(result => {
    cy.log(result); // prints the _id of inserted document
});

cy.insertMany([{document: 1}, {document: 2}]); // will insert provided documents in mongodb

cy.insertMany([{document: 1}, {document: 2}], {collection: 'some_other_collection'}).then(result => {
    console.log(result); // prints the key-value pairs of the inserted ids
});

Find commands

> syntax

cy.findOne(query);
cy.findOne(query, options);

cy.findMany(query);
cy.findMany(query, options);

cy.findOneAndUpdate(filter);
cy.findOneAndUpdate(filter, options);

cy.findOneAndDelete(filter);
cy.findOneAndDelete(filter, options);

> arguments

ArgumentsTypeDescription
queryObject (required)Specifies query selection criteria using query operators
filterObject (required)The selection criteria for the deletion
optionsObject (optional)Provide additional options (see below)

> options

OptionsDefaultDescription
collectionValue specified in the mongodb environment variableDatabase on top of which the command will be executed
databaseValue specified in the mongodb environment variableCollection on top of which the command will be executed
upsertfalseCreates a new document if no documents matched the provided filter (used only in findOneAndUpdate command)
returnDocumentbeforeSpecify this option with after value to return the update document instead of the original one (used only in findOneAndUpdate command)
sortFirst matching documentSpecifies a sorting order for the documents matched by the filter (used only in findOneAndDelete command)
projectionEntire documentA subset of fields to return (used only in findOneAndDelete command)

> examples

import { ObjectId } from 'mongodb';
cy.findOne({_id: new ObjectId()}).then(result => {
    cy.log(result); // prints the document with the _id if found, otherwise null
});

cy.findMany({document: 1}).then(result => {
    cy.log(result); // prints the array of documents if any matched, or empty array
});

cy.findOneAndUpdate({ document: 2 }, { $set: { document: 3 }).then(result => {
  cy.log(result); // prints the original document with value 2
});
cy.findOneAndUpdate({ document: 3 }, { $set: { document: 4 }, {upsert: true, returnDocument: 'after'}).then((result: any) => {
  cy.log(result); // prints the updated document with the value 4, will create (upsert) a new document if none are found
});

Update commands

> syntax

cy.updateOne(filter, update);
cy.updateOne(filter, update, options);

cy.updateMany(filter, update);
cy.updateMany(filter, update, options);

> arguments

ArgumentsTypeDescription
filterObject (required)The selection criteria for the update
updateObject or pipeline (required)The modifications to apply
optionsObject (optional)Provide additional options (see below)

> options

OptionsDefaultDescription
collectionValue specified in the mongodb environment variableDatabase on top of which the command will be executed
databaseValue specified in the mongodb environment variableCollection on top of which the command will be executed
upsertfalseIf set to true, creates a new document if no documents match the filter

> examples

cy.updateOne({document: 1}, { $set: { document: 2 } }, { upsert: true }).then(result => {
    cy.log(result); // prints the object containing the update info: matchedCount, modifiedCount, upsertedCount, etc
});

cy.updateMany({document: 1}, { $set: { document: 2 } }, { upsert: true }).then(result => {
    cy.log(result); // prints the object containing the update info: matchedCount, modifiedCount, upsertedCount, etc
});

Delete commands

> syntax

cy.deleteOne(filter);
cy.deleteOne(filter, options);

cy.deleteMany(filter);
cy.deleteMany(filter, options);

> arguments

ArgumentsTypeDescription
filterObject (required)Specifies deletion criteria using query operators
optionsObject (optional)Provide additional options (see below)

> options

OptionsDefaultDescription
collectionValue specified in the mongodb environment variableDatabase on top of which the command will be executed
databaseValue specified in the mongodb environment variableCollection on top of which the command will be executed

> examples

cy.deleteOne({document: 1}); // will delete a first matched document

cy.deleteOne({document: 1}, {collection: 'new_collection', database: 'some_database'}).then(result => {
    cy.log(result); // prints 1 (or 0) document deleted
});

cy.deleteMany(deleteClause).then(res => {
    cy.log(result); // prints '# documents deleted'
});

Aggregate commands

> syntax

cy.aggregate(pipeline);
cy.aggregate(pipeline, options);

> arguments

ArgumentsTypeDescription
pipelineObject[] (required)An array of object representing a sequence of data aggregation operations or stages
optionsObject (optional)Provide additional options (see below)

> options

OptionsDefaultDescription
collectionValue specified in the mongodb environment variableDatabase on top of which the command will be executed
databaseValue specified in the mongodb environment variableCollection on top of which the command will be executed

> examples

const pipeline = []; // any kind of aggregation
cy.aggregate(pipeline).then(result => {
    cy.log(result); // prints the result of the aggregation
});

Reference

https://mongodb.github.io/node-mongodb-native/4.10/classes/Collection.html

Future development & support

Please create feature requests for things you'd like to see.
Please raise issues for any problems you encounter.

Keywords

FAQs

Package last updated on 29 May 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc