You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
18 Hrs
10 Min
19 Seg

Pruebas con base de datos NoSQL con MongoDB

13/17
Resources

How to test NoSQL databases with MongoDB?

In this fascinating walkthrough you will learn how to test NoSQL databases, using MongoDB, one of the most common solutions in this field. However, the principles you will see here are applicable to other NoSQL databases such as Firebase, so find out how to interact with your database efficiently and smoothly!

What are the steps to install and configure MongoDB?

Before starting, you need to install the MongoDB library. Once installed, you will be able to create an asynchronous function called connect that allows you to connect to the MongoDB client. This function is crucial to access the database and get the necessary collections.

// Install the MongoDB libraryconst { MongoClient } = require('mongodb');
// Create connection functionasync function connect(client) { await client.connect(); return client.db();}

In the above code, MongoClient is a class provided by MongoDB that allows you to interact with the database. In addition, MongoDB Atlas is a recommended option to create Mongo databases for free.

How to perform queries and handle errors?

Once the connection is set up, it is time to build functions to perform queries. Here it is vital to handle errors and close connections correctly, ensuring that no open connections are left open that may cause inefficiencies.

async function getAsyncGetListing(client) { try { const db = await connect(client); const listingsAndReviews = await db.collection('listingsAndReviews') .find() .limit(50) .toArray(); return listingsAndReviews; } catch (error) { console.error('Error:', error); } finally { await client.close(); } }}

With this function, the listingsAndReviews collection is accessed, using find to perform the query and limit to restrict the number of results, thus ensuring optimized data handling.

How to create tests and solve common problems?

Testing functionality is essential. To do so, a test file is created to verify that the data obtained meets the expected criteria. In doing so, problems may arise such as connection errors, which are usually related to network configurations.

describe('Testing Mongo', () => { it('Should perform a Mongo select', async () => { const results = await getListing(); expect(results).toHaveLength(50); }); }); });

In case you get an error like "connection timeout", it is important to check that the IP address is correctly added to the network access configuration. This is necessary due to security reasons in MongoDB.

What role do best practices play in NoSQL?

In NoSQL databases, we cannot simply execute a query string as in SQL databases. Here it is essential to use functions such as find and limit to collect and manage the data. This is due to the nature of relational and non-relational databases.

Throughout this process, you have gained valuable knowledge that will optimize your interaction with NoSQL databases. Keep discovering more about the potentialities offered by these technologies and continue to expand your skills in this exciting field!

Contributions 5

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

luego de este curso hare uno de DB, me perdi un poco 😢

Para Cypress 12 lo que hcie en mi caso fue lo siguiente:

Por defecto utilice la conexion que te da Mongo al momento de instalarlo y el URI en el archivo cypress.env.json lo puse asi:

"mongo": "mongodb://127.0.0.1:27017/"

|
Este lo pueden sacar desde la opción Copy connection string en MongoDB Compass
|
NOTA: Esta con 127.0.0.1 debido a que con localhost falla y según leí es debido a que con localhost Mongo utiliza una dirección IPv6 y al darle el valor de 127.0.0.1 utiliza la dirección de localhost pero de IPv4
|
La conexion la configure asi en el archivo cypress.config.js

const { defineConfig } = require("cypress");
const { MongoClient } = require("mongodb");
const mysql = require('mysql')

module.exports = defineConfig({
  e2e: {
    baseUrl: "https://localhost:3000/",
    setupNodeEvents(on, config) {
      // implement node event listeners here
      on('task',{
        queryTestDb:function(query) {
        const connection = mysql.createConnection(config.env.db)
        connection.connect()
        return new Promise((resolve, reject) => {
          connection.query(query,(err,results)=>{
            if(err){
              reject(err)
            } else {

              connection.end()
              return resolve(results)
            }
          })
        })
      },
      queryMongo: async function(object) {
        let client;
        try {
          client = new MongoClient(config.env.mongo);
          await client.connect();
          console.log("Connected to MongoDB");
  
          const db = client.db('cypress');
          const collection = db.collection("tests");
          const results = await collection.find(object).toArray();
          return results;
        } catch (e) {
          console.error("Error connecting to MongoDB", e);
          throw e;
        } finally {
          if (client) {
            await client.close();
            console.log("Disconnected from MongoDB");
          }
        }
      }
    })
    },
    excludeSpecPattern:[
      "**/1-getting-started/*.js",
      "**/2-advanced-examples/*.js"
    ]
  }
});

En mi caso me cree una base de datos llamada cypress y dentro una coleccion llamada tests, el objeto que cree solo para tener informacion que recuperar de dicha coleccion es {Name: ‘Mauricio’}
|
Y finalmente para el test puse lo siguiente:

describe("Testing mongo", function() {
    it('Listing mongo', function () {
      let object = { Name: "Mauricio" };
      cy.task("queryMongo", object).then((results) => {
        cy.log(results);
        expect(results).to.have.length(1);
        expect(results[0].Name).to.be.eq("Mauricio")
      });
    });
});

¡Rock n’ Roll! 🤟

Qué complicado…

En este link escuentran mi solucion: <https://github.com/celioso/Cursos-de-Platzi/tree/main/CursoDeAutomatizacionDePruebasDeBackendConCypress>