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
2 Hrs
47 Min
25 Seg

Tu primer prueba e2e

5/25
Resources

How to write your first test in Twen?

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.

What would Insomnia or Postman do, but in an automatic way?

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.

Which tool to use for end-to-end testing in Node?

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.

Installing Supertest

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.

How to create a basic Express server with an endpoint?

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.

How to test an endpoint with Supertest?

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/); });});

Explanation of the test code

  1. Requests: We use request(app).get('/hello') to send a GET request to the /hello endpoint.

  2. Checks (expectations):

    • We verify that the status code is 200.
    • We check that the response body contains the name 'Nico'.
    • Confirm that the content type returned is JSON.
  3. 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.

What to do if tests fail or there are asynchronous problems?

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:

  • Verify the expected and application status code.
  • Analyze the server responses to make sure they match what is specified in the test.

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

Sort by:

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

👉 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:

  1. Assertions Integradas: Jest incluye un conjunto de aserciones (assertions) integradas que permiten verificar que los resultados de las funciones y componentes sean los esperados.

  2. 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.

  3. 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.

  4. 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:

  1. Solicitudes HTTP Simuladas: Supertest permite realizar solicitudes HTTP (GET, POST, PUT, DELETE, etc.) a una API simulada o en ejecución.

  2. Evaluación de Respuestas: Con Supertest, puedes verificar las respuestas HTTP recibidas, como los códigos de estado, encabezados y cuerpo de respuesta.

  3. 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.

No se necesita corrar la api `app.listen(PORT)`, para poder correr las pruebas con supertest
La UI de Postman es mejor que Insomnia
Muy interesante esta clase