luego de este curso hare uno de DB, me perdi un poco 😢
Introduccion a la Automatización Backend
¿Ya tomaste el Curso de Automatización de Pruebas UI con Cypress?
Backend testing
Herramientas del Navegador
Conociendo Cypress
Preparando nuestro entorno de trabajo
Probando el header
Probando el status code
Validando el contenido de la respuesta
Validando el body
Validando un error
Haciendo diferentes tipos de peticiones
Peticiones REST
Peticiones GraphQL
Bases de Datos
Preparando nuestro entorno para base de datos
Probar con bases de Datos SQL
Pruebas con base de datos NoSQL con MongoDB
Limpiar y crear base de datos NoSQL con MongoDB
Prueba en conjunto
Pruebas en conjunto: API y Base de Datos
Próximos pasos
¿Quieres un Curso de Cypress Avanzado?
Oferta laboral de Cypress en México (temporal)
You don't have access to this class
Keep learning! Join and start boosting your career
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!
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.
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.
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.
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
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…
Want to see more contributions, questions and answers from the community?