👉 Si desean tener autocompletado en los archivos, pueden instalar los tipos de jest:
NPM
npm i @types/jest --save-dev
Yarn
yarn add -D @types/jest
Requisitos
¿Qué necesitas para aprender Testing E2E con Node.js?
Introducción: pruebas e2e con Node.js
Explorando la API
Explorando el código del proyecto
Instalando y configurando Jest con Node
Tu primer prueba e2e
Buenas prácticas en pruebas E2E
Pruebas a la API de Fake Store
Configurando el entorno de pruebas para nuestro proyecto
Coverage Report
Pruebas a Schemas o DTOs
Pruebas a endpoints GET
Pruebas al Login
Pruebas a rutas con protección
Pruebas a rutas con accessToken
Pruebas a endpoints POST
Pruebas en Entornos de Desarrollo Avanzados
¿Crear bases de datos solo para pruebas?
Preparando el ambiente de pruebas e2e
Creando un seed de datos manual
Seed de datos con sequelize
Umzug: corriendo los seeds de datos para pruebas e2e
Pruebas a crear categorías
Pruebas al endpoint de producto
Pruebas a la paginación
Mocking y automatización
Mocking en Node.js
Automatizacion en GitHub Actions
Próximos pasos
¿Quieres más cursos de testing?
You don't have access to this class
Keep learning! Join and start boosting your career
Writing tests for web applications is essential to ensure that your software works correctly in several cases. An excellent example is the use of Twen to write tests that simulate HTTP requests to our Node.js server, similar to what we do with tools like Postman or Insomnia. The difference is that, with Twen, we can automate and professionalize this process.
Programs like Insomnia or Postman allow you to make manual HTTP requests to a server to get responses. However, these are not tests as such, but simply simulations of requests. Twen, on the other hand, goes one step further. It automatically sends multiple tests to a single endpoint to verify aspects such as response status code, data validation and server connectivity. Thus, we can ensure that the application works correctly under different scenarios.
To perform similar tests in an automated way in Node.js, we use Supertest. This tool is ideal for emulating HTTP requests and verifying their responses programmatically. Like Yes, Supertest is installed as a development dependency.
Open your terminal and proceed to install Supertest using the following command, making sure you are in the right working environment:
npm install --save-dev supertest
With the tool installed, we can proceed to create and test endpoints in our Express application.
First, we will set up a simple Express application that will serve as the basis for our tests:
const express = require('express');const app = express();
app.get('/hello', (req, res) => { res.status(200).json({ name: 'Nico' });});
app.listen(9000, () => { console.log('Server is running on port 9000');});
This code creates a small Express server with an endpoint called /hello
, which responds with a JSON containing a name. Now, we must prepare the tests for this server.
Supertest allows us to define our tests as follows:
const request = require('supertest');
describe('Tests for endpoint /hello', () => { it('Must respond with a status 200 and an expected JSON', async () => { const response = await request(app).get('/hello'); expect(response.statusCode).toEqual(200); expect(response.body.name).toEqual('Nico'); expect(response.headers['content-type']).toMatch(/json/); });});
Requests: We use request(app).get('/hello')
to send a GET request to the /hello
endpoint.
Checks (expectations):
Test run: To run these tests, we use the command for our test environment, which usually involves a testing tool such as jest
.
npx jest
Running the above command will validate that all the tests defined in the file run correctly.
During the execution of tests, you might encounter errors if the server response does not match what is expected. Precisely, if we request a 200 status code but get a 201, for example, the test will fail. To solve this:
In addition, it is common to encounter warnings about unfinished asynchronous processes. This problem arises when the Express server does not stop after testing. You can close these processes at the end of all tests or by modifying the configuration of your testing tools.
Automated testing is essential for modern development, so don't stop here and keep exploring tools and methodologies that ensure the quality of your software!
Contributions 5
Questions 0
👉 Si desean tener autocompletado en los archivos, pueden instalar los tipos de jest:
NPM
npm i @types/jest --save-dev
Yarn
yarn add -D @types/jest
Jest y Supertest son dos herramientas que se utilizan comúnmente en el desarrollo de software en JavaScript para probar y evaluar aplicaciones, pero se enfocan en aspectos diferentes:
Jest:
Jest es un framework de pruebas unitarias y de integración para JavaScript. Se utiliza para escribir y ejecutar pruebas automatizadas que verifican el comportamiento de las diferentes partes de una aplicación. Jest proporciona una amplia gama de utilidades y funciones para escribir pruebas de manera efectiva. Algunas características destacadas de Jest incluyen:
Assertions Integradas: Jest incluye un conjunto de aserciones (assertions) integradas que permiten verificar que los resultados de las funciones y componentes sean los esperados.
Mocks y Espías: Jest ofrece herramientas para crear mocks y espías, lo que facilita la simulación de componentes o módulos externos en las pruebas.
Testing Asincrónico: Jest maneja de manera efectiva las pruebas asincrónicas utilizando funciones como async/await
o el uso de las funciones globales setTimeout
y setInterval
.
Snapshot Testing: Jest es conocido por su característica de “snapshot testing”, que permite capturar el estado actual de un componente y luego compararlo con futuras ejecuciones para detectar cambios no deseados.
Supertest:
Supertest, por otro lado, es una biblioteca que se utiliza para probar APIs HTTP en aplicaciones Node.js. Su principal objetivo es simular solicitudes HTTP y evaluar las respuestas obtenidas desde una perspectiva externa. Algunas características de Supertest son:
Solicitudes HTTP Simuladas: Supertest permite realizar solicitudes HTTP (GET, POST, PUT, DELETE, etc.) a una API simulada o en ejecución.
Evaluación de Respuestas: Con Supertest, puedes verificar las respuestas HTTP recibidas, como los códigos de estado, encabezados y cuerpo de respuesta.
Uso con Otros Marcos de Pruebas: Supertest se utiliza comúnmente en combinación con frameworks de pruebas como Mocha o Jest para probar APIs y servicios.
En resumen, Jest se enfoca en las pruebas unitarias e integración de código JavaScript en general, mientras que Supertest está diseñado específicamente para probar APIs HTTP y servicios en Node.js. Dependiendo de tus necesidades, podrías utilizar Jest para probar la lógica interna de tus componentes y funciones, y Supertest para probar las interacciones HTTP de tu aplicación.
Want to see more contributions, questions and answers from the community?