Pruebas sin dependencias con Node.js

Rate this content
Bookmark

Node.js recientemente lanzó un runner de pruebas experimental. Esta charla explorará la arquitectura y API del runner de pruebas, y mostrará cómo usarlo con otros módulos principales para crear una experiencia de pruebas sin dependencias externas. Esta charla también examinará posibles adiciones futuras al runner de pruebas.

10 min
03 Nov, 2022

Video Summary and Transcription

La charla de hoy trata sobre las pruebas sin dependencias con Node.js. El nuevo runner de pruebas en Node.js admite la ejecución de la línea de comandos (CLI) y la ejecución de archivos independientes, y admite diferentes estilos de runner de pruebas. Es simple escribir pruebas con Node.js utilizando sus módulos assert y test. El runner de pruebas pasó una prueba y falló en otra, y el trabajo futuro incluye la implementación de un analizador tap y la adición de características de cobertura de código y simulación.

Available in English

1. Zero Dependency Testing with Node.js

Short description:

Hoy voy a hablar sobre las pruebas sin dependencias con Node.js. Casi todos los proyectos necesitan un ejecutor de pruebas. Node.js tiene una buena biblioteca de aserciones, lo que reduce las dependencias. Muchos ejecutores de pruebas tienen funcionalidades superpuestas. Tener un ejecutor de pruebas incorporado reduce los riesgos y los costos. La tendencia es incluir ejecutores de pruebas en los entornos de ejecución. El nuevo ejecutor de pruebas en Node admite la interfaz de línea de comandos (CLI) y la ejecución de archivos independientes. Admite pruebas síncronas, promesas, asíncronas/await y basadas en devoluciones de llamada. Se admiten diferentes estilos de ejecutores de pruebas.

¡Hola a todos! Gracias por venir a mi charla. Hoy voy a hablar sobre las pruebas sin dependencias con Node.js, lo que significa que puedes comenzar a escribir tus pruebas unitarias, pruebas de integración, sin tener que instalar nada desde NPM.

Antes de adentrarnos en la naturaleza del nuevo ejecutor de pruebas de Node, quería hablar un poco sobre por qué se deseaba un ejecutor de pruebas en primer lugar. Casi todos los proyectos necesitan un ejecutor de pruebas. Ya sea que estés construyendo una aplicación o un módulo que planeas publicar en NPM o cualquier otra cosa, si planeas que otras personas usen tu código, casi seguramente necesitas pruebas para ello. Y luego, Node.js ha incluido desde hace años una biblioteca de aserciones realmente buena que se importa simplemente como assert. Esta es la biblioteca de aserciones que he estado usando durante años. Me gusta, así que eso es una dependencia menos. Y luego, la mayoría de los ejecutores de pruebas se superponen mucho en términos de funcionalidad de todos modos. Así que, ya sabes, cada ejecutor de pruebas ejecuta algunas pruebas. Por lo general, tienen características como tiempos de espera, informes sobre qué pruebas pasaron y fallaron, saltar pruebas, cosas así. Así que, hay diferencias, algunos ejecutores de pruebas son más adecuados para el desarrollo front-end, algunos hacen cosas como inyectar variables globales en tu código sin que lo sepas, algunos ejecutan sus pruebas dentro de diferentes contextos, por lo que podrías tener resultados sorprendentes cuando verifiques la igualdad y cosas así. Pero, ya sabes, hay estas pequeñas imperfecciones, pero en general, muchos ejecutores de pruebas tienen muchas funcionalidades superpuestas.

Y además, NPM es realmente un lugar peligroso. A lo largo de los años, ha habido varios incidentes, como left pad, la cosa de colors JS, incluso más recientemente, el paquete minimist, que creo que tiene como 50 millones de descargas o algo así, no le pasó nada en NPM, pero el repositorio de GitHub desapareció. Así que, todas estas dependencias de terceros que estás asumiendo conllevan ciertos riesgos y costos. Y eso es solo una razón por la cual tener un ejecutor de pruebas incorporado, creo, es útil. Y también, hay una tendencia general a tener más de estas cosas incluidas en los entornos de ejecución. Así que, ya sabes, ahora Node tiene un ejecutor de pruebas incorporado. Estoy bastante seguro de que Bun tiene uno, sé que Deno tiene uno. Esto se está volviendo cada vez más común. Y luego, aquí está mi tweet de hace más de un año, creo que Node debería incluir un ejecutor de pruebas y, ya sabes, me siento bastante seguro al respecto. Algunas de las características del nuevo ejecutor de pruebas, puedes ejecutarlo a través de la interfaz de línea de comandos (CLI) que ahora tiene Node con la bandera --test. O puedes ejecutar un archivo independiente que contenga pruebas. Así que, digamos que tienes tu archivo foo.js, puedes decir Node foo.js y si estás usando el ejecutor de pruebas allí, seguirá funcionando. En cuanto a escribir las pruebas en sí, admitimos código síncrono, código basado en promesas o async/await. E incluso, ya sabes, porque Node todavía tiene muchas API basadas en devoluciones de llamada, también admitimos pruebas basadas en devoluciones de llamada. Si vienes de un ejecutor de pruebas como tap o tape, entonces admitimos pruebas de estilo tap, utilizando la función test. Si vienes de un ejecutor de pruebas como Mocha o Jest, tenemos las funciones describe e IT. Bajo el capó, todo utiliza test, describe e IT se implementan de manera similar.

2. Writing Tests with Node.js

Short description:

Si estás buscando esa API familiar, está ahí. Admitimos pruebas anidadas, saltar pruebas y filtrar pruebas por nombre. Escribir una prueba es sencillo con los módulos assert y test de Node. El ejecutor de pruebas se publica en NPM y admite Node 14, 16 y 18. Después de ejecutar las pruebas, la salida sigue el protocolo de pruebas anything (tap).

parte superior de la prueba. Pero, ya sabes, si estás buscando esa API familiar, está ahí. Admitimos pruebas anidadas, por lo que puedes tener, ya sabes, una prueba con pruebas arbitrariamente anidadas dentro de ella. Lo mismo si tienes describe. Puedes tener suites que contengan más suites y más pruebas y cosas así. Saltar y hacer pruebas. Así que, ya sabes, si solo quieres saltar una prueba, hay varias formas diferentes de hacerlo. Hacer es similar a saltar en el sentido de que no hará que tu conjunto de pruebas falle. Pero aún ejecutará la prueba y no le importará el resultado. También tenemos solo pruebas. Entonces, si inicias el ejecutor de pruebas de la CLI con guión guión solo pruebas, solo se ejecutarán las pruebas que hayas anotado como solo pruebas. Y también puedes filtrar las pruebas por el nombre de la prueba. Entonces, si usas el patrón de nombre de prueba guión guion guion, en realidad puedes pasar una expresión regular y node solo ejecutará las pruebas cuyos nombres coincidan con ese patrón. Entonces, si quisieras escribir una prueba, ¿cómo se vería? Aquí tienes un ejemplo muy sencillo que utiliza solo el módulo assert de node y el módulo de pruebas de node. Aquí tenemos dos pruebas. Una es una prueba sincrónica que pasa y la otra es una prueba asíncrona que falla. La prueba asíncrona, aunque parece código sincrónico, es una función asíncrona, por lo que devuelve una promesa. Esa promesa se rechaza cuando la aserción falla. Entonces, dos cosas que vale la pena mencionar aquí es que verás que estamos usando node dos puntos prueba. El prefijo node dos puntos se puede usar para importar cualquier módulo principal de node. Pero a partir del módulo de prueba y probablemente con todos los módulos agregados al núcleo de node en el futuro, debes usar el prefijo node dos puntos. Si intentas usar solo la palabra prueba aquí, en realidad intentará cargar desde el espacio de usuario. Y hablando del espacio de usuario, el ejecutor de pruebas en sí está publicado en NPM. Por ahora, el ejecutor de pruebas existe en node 18 y 16. Node 14 aún es compatible, sin embargo. Entonces, algunas personas tomaron el código del núcleo de node, lo adaptaron para que funcione en un módulo de NPM, y lo publicaron. Entonces, simplemente puedes instalar prueba si estás en node 14 y aún tendrás acceso a todas estas funcionalidades. Después de ejecutar tus pruebas, esto es cómo se verá la salida. Esta salida se llama tap, que significa protocolo de pruebas anything. Y no es la más fácil de analizar para los humanos, pero puedes hacer cosas interesantes como, ya sabes, redirigirla a diferentes informes y cosas así, y tener un formato diferente. Pero puedes ver aquí que tenemos okay 1, esa es la primera prueba, que fue la sincrónica que pasó

3. Resultados del Ejecutor de Pruebas y Trabajo Futuro

Short description:

El ejecutor de pruebas pasó una prueba y falló otra. El fallo de la prueba se debió a una aserción que esperaba que el valor 1 fuera igual a 2. El resumen de las pruebas mostró que se ejecutaron dos pruebas, una pasó y otra falló. Todo el proceso tomó aproximadamente 11 milisegundos. El trabajo futuro para el ejecutor de pruebas incluye implementar un analizador de tap para obtener mejores informes, desarrollar informes para transformar la salida de tap y agregar cobertura de código y funciones de simulación. El ejecutor de pruebas aún está en fase experimental, pero no se esperan cambios importantes. ¡Consulta la documentación y pruébalo!

prueba. Pasó en 1.87 milisegundos. Y luego la segunda prueba no estuvo bien. No estar bien es cómo tap indica un fallo. Puedes ver que hubo un fallo en el código de la prueba. Esperábamos la aserción... afirmamos que el valor 1 sería igual a 2, y claramente no lo es. Así que la prueba falló.

Y luego en la parte inferior, tenemos un pequeño resumen de las pruebas. Se ejecutaron dos pruebas que una pasó, una falló, cero se cancelaron, cero se omitieron. No hay pruebas pendientes. Y luego todo el proceso tomó aproximadamente 11 milisegundos.

Así que solo algunas de las tareas futuras para el ejecutor de pruebas. Tenemos una solicitud de extracción que está abierta en este momento para un analizador de tap. Esto nos permitirá obtener mejores informes dentro del ejecutor de pruebas de la CLI. La CLI para cada archivo que va a ejecutar, genera un proceso secundario que genera su propio tap. La forma en que funciona ahora es que si hay un fallo, simplemente tomamos toda la salida estándar y el error estándar de ese archivo y lo mostramos. Si no hay pruebas fallidas, entonces simplemente decimos que pasó y no mostramos ninguna salida. El analizador de tap nos permitirá analizar inteligentemente esa salida y mostrar las cosas de manera más agradable. También queremos usar el analizador de tap para desarrollar informes. Como dije antes, tap no es lo más bonito de ver. Queremos implementar algunos informes que puedan transformarlo en algo un poco más fácil de leer para los humanos. Luego nos gustaría agregar cobertura de código y simulación, porque estas son dos características bastante importantes que realmente hacen que un ejecutor de pruebas se sienta maduro, en mi opinión. Así que el ejecutor de pruebas aún se considera experimental, pero no espero que haya muchos, si es que hay alguno, cambios importantes en él. Tengo aquí un enlace a la documentación. Animo a todos a que lo prueben al menos una vez. Eso es todo lo que tenía. Gracias por venir. Adiós.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
Do you have a large product built by many teams? Are you struggling to release often? Did your frontend turn into a massive unmaintainable monolith? If, like me, you’ve answered yes to any of those questions, this talk is for you! I’ll show you exactly how you can build a micro frontend architecture with Remix to solve those challenges.
TestJS Summit 2021TestJS Summit 2021
33 min
Network Requests with Cypress
Top Content
Whether you're testing your UI or API, Cypress gives you all the tools needed to work with and manage network requests. This intermediate-level task demonstrates how to use the cy.request and cy.intercept commands to execute, spy on, and stub network requests while testing your application in the browser. Learn how the commands work as well as use cases for each, including best practices for testing and mocking your network requests.
TestJS Summit 2021TestJS Summit 2021
38 min
Testing Pyramid Makes Little Sense, What We Can Use Instead
Top Content
Featured Video
The testing pyramid - the canonical shape of tests that defined what types of tests we need to write to make sure the app works - is ... obsolete. In this presentation, Roman Sandler and Gleb Bahmutov argue what the testing shape works better for today's web applications.
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
Remix is a web framework that gives you the simple mental model of a Multi-Page App (MPA) but the power and capabilities of a Single-Page App (SPA). One of the big challenges of SPAs is network management resulting in a great deal of indirection and buggy code. This is especially noticeable in application state which Remix completely eliminates, but it's also an issue in individual components that communicate with a single-purpose backend endpoint (like a combobox search for example).
In this talk, Kent will demonstrate how Remix enables you to build complex UI components that are connected to a backend in the simplest and most powerful way you've ever seen. Leaving you time to chill with your family or whatever else you do for fun.
JSNation Live 2021JSNation Live 2021
29 min
Making JavaScript on WebAssembly Fast
Top Content
JavaScript in the browser runs many times faster than it did two decades ago. And that happened because the browser vendors spent that time working on intensive performance optimizations in their JavaScript engines.Because of this optimization work, JavaScript is now running in many places besides the browser. But there are still some environments where the JS engines can’t apply those optimizations in the right way to make things fast.We’re working to solve this, beginning a whole new wave of JavaScript optimization work. We’re improving JavaScript performance for entirely different environments, where different rules apply. And this is possible because of WebAssembly. In this talk, I'll explain how this all works and what's coming next.
React Summit 2023React Summit 2023
24 min
Debugging JS
Top Content
As developers, we spend much of our time debugging apps - often code we didn't even write. Sadly, few developers have ever been taught how to approach debugging - it's something most of us learn through painful experience.  The good news is you _can_ learn how to debug effectively, and there's several key techniques and tools you can use for debugging JS and React apps.

Workshops on related topic

React Summit 2023React Summit 2023
151 min
Designing Effective Tests With React Testing Library
Top Content
Featured Workshop
React Testing Library is a great framework for React component tests because there are a lot of questions it answers for you, so you don’t need to worry about those questions. But that doesn’t mean testing is easy. There are still a lot of questions you have to figure out for yourself: How many component tests should you write vs end-to-end tests or lower-level unit tests? How can you test a certain line of code that is tricky to test? And what in the world are you supposed to do about that persistent act() warning?
In this three-hour workshop we’ll introduce React Testing Library along with a mental model for how to think about designing your component tests. This mental model will help you see how to test each bit of logic, whether or not to mock dependencies, and will help improve the design of your components. You’ll walk away with the tools, techniques, and principles you need to implement low-cost, high-value component tests.
Table of contents- The different kinds of React application tests, and where component tests fit in- A mental model for thinking about the inputs and outputs of the components you test- Options for selecting DOM elements to verify and interact with them- The value of mocks and why they shouldn’t be avoided- The challenges with asynchrony in RTL tests and how to handle them
Prerequisites- Familiarity with building applications with React- Basic experience writing automated tests with Jest or another unit testing framework- You do not need any experience with React Testing Library- Machine setup: Node LTS, Yarn
TestJS Summit 2022TestJS Summit 2022
146 min
How to Start With Cypress
Featured WorkshopFree
The web has evolved. Finally, testing has also. Cypress is a modern testing tool that answers the testing needs of modern web applications. It has been gaining a lot of traction in the last couple of years, gaining worldwide popularity. If you have been waiting to learn Cypress, wait no more! Filip Hric will guide you through the first steps on how to start using Cypress and set up a project on your own. The good news is, learning Cypress is incredibly easy. You'll write your first test in no time, and then you'll discover how to write a full end-to-end test for a modern web application. You'll learn the core concepts like retry-ability. Discover how to work and interact with your application and learn how to combine API and UI tests. Throughout this whole workshop, we will write code and do practical exercises. You will leave with a hands-on experience that you can translate to your own project.
React Summit 2022React Summit 2022
117 min
Detox 101: How to write stable end-to-end tests for your React Native application
Top Content
WorkshopFree
Compared to unit testing, end-to-end testing aims to interact with your application just like a real user. And as we all know it can be pretty challenging. Especially when we talk about Mobile applications.
Tests rely on many conditions and are considered to be slow and flaky. On the other hand - end-to-end tests can give the greatest confidence that your app is working. And if done right - can become an amazing tool for boosting developer velocity.
Detox is a gray-box end-to-end testing framework for mobile apps. Developed by Wix to solve the problem of slowness and flakiness and used by React Native itself as its E2E testing tool.
Join me on this workshop to learn how to make your mobile end-to-end tests with Detox rock.
Prerequisites- iOS/Android: MacOS Catalina or newer- Android only: Linux- Install before the workshop
React Day Berlin 2022React Day Berlin 2022
86 min
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
Top Content
WorkshopFree
Using a library might seem easy at first glance, but how do you choose the right library? How do you upgrade an existing one? And how do you wade through the documentation to find what you want?
In this workshop, we’ll discuss all these finer points while going through a general example of building a code editor using CodeMirror in React. All while sharing some of the nuances our team learned about using this library and some problems we encountered.
TestJS Summit 2023TestJS Summit 2023
48 min
API Testing with Postman Workshop
Top Content
WorkshopFree
In the ever-evolving landscape of software development, ensuring the reliability and functionality of APIs has become paramount. "API Testing with Postman" is a comprehensive workshop designed to equip participants with the knowledge and skills needed to excel in API testing using Postman, a powerful tool widely adopted by professionals in the field. This workshop delves into the fundamentals of API testing, progresses to advanced testing techniques, and explores automation, performance testing, and multi-protocol support, providing attendees with a holistic understanding of API testing with Postman.
1. Welcome to Postman- Explaining the Postman User Interface (UI)2. Workspace and Collections Collaboration- Understanding Workspaces and their role in collaboration- Exploring the concept of Collections for organizing and executing API requests3. Introduction to API Testing- Covering the basics of API testing and its significance4. Variable Management- Managing environment, global, and collection variables- Utilizing scripting snippets for dynamic data5. Building Testing Workflows- Creating effective testing workflows for comprehensive testing- Utilizing the Collection Runner for test execution- Introduction to Postbot for automated testing6. Advanced Testing- Contract Testing for ensuring API contracts- Using Mock Servers for effective testing- Maximizing productivity with Collection/Workspace templates- Integration Testing and Regression Testing strategies7. Automation with Postman- Leveraging the Postman CLI for automation- Scheduled Runs for regular testing- Integrating Postman into CI/CD pipelines8. Performance Testing- Demonstrating performance testing capabilities (showing the desktop client)- Synchronizing tests with VS Code for streamlined development9. Exploring Advanced Features - Working with Multiple Protocols: GraphQL, gRPC, and more
Join us for this workshop to unlock the full potential of Postman for API testing, streamline your testing processes, and enhance the quality and reliability of your software. Whether you're a beginner or an experienced tester, this workshop will equip you with the skills needed to excel in API testing with Postman.
TestJS Summit - January, 2021TestJS Summit - January, 2021
173 min
Testing Web Applications Using Cypress
WorkshopFree
This workshop will teach you the basics of writing useful end-to-end tests using Cypress Test Runner.
We will cover writing tests, covering every application feature, structuring tests, intercepting network requests, and setting up the backend data.
Anyone who knows JavaScript programming language and has NPM installed would be able to follow along.