Zero Dependency Testing With Node.js

Rate this content
Bookmark

Node.js recently shipped an experimental test runner. This talk will explore the test runner's architecture and API, and show how to use it with other core modules to create a testing experience with no external dependencies. This talk will also look at potential future additions to the test runner.

This talk has been presented at TestJS Summit 2022, check out the latest edition of this Tech Conference.

FAQ

Zero dependency testing with Node.js means writing unit and integration tests without needing to install any additional packages from NPM.

A test runner is essential for Node.js projects to automate the execution of tests, report passed and failed tests, and handle features like timeouts and skipping tests, ensuring code quality and reliability.

Node's new test runner supports synchronous code, promises, async/await, and callback-based tests. It includes features like nesting tests, describe and it functions, skip and todo tests, only tests, and filtering tests by name pattern.

You can run tests using Node's built-in test runner through the CLI with the --test flag or by executing a standalone file containing tests using Node's CLI.

Using Node's built-in test runner reduces dependency risks associated with third-party packages from NPM, avoids issues like package removal or vulnerabilities, and follows the trend of having more built-in features in runtimes.

Skip tests do not execute and do not cause the test suite to fail, while todo tests execute but do not affect the test suite's pass/fail status.

Yes, you can filter tests by name using the --test-name-pattern flag with a regular expression to only execute tests that match the specified pattern.

TAP (Test Anything Protocol) is the output format used by Node's test runner, which includes information about test pass/fail status, execution time, and a summary of test results.

Node's new test runner is available in Node.js versions 18 and 16. For Node.js 14, the test runner is available as an NPM package that can be installed separately.

Future plans for Node's test runner include implementing a TAP parser for better reporting, building out reporters for more readable output, and adding features like code coverage and mocking.

Colin Ihrig
Colin Ihrig
10 min
03 Nov, 2022

Comments

Sign in or register to post your comment.

Video Summary and Transcription

Today's Talk is about zero dependency testing with Node.js. The new test runner in Node.js supports CLI and standalone file execution, and different test runner styles are supported. Writing tests with Node.js is simple using its assert and test modules. The test runner passed one test and failed another, and future work includes implementing a tap parser and adding code coverage and mocking features.

1. Zero Dependency Testing with Node.js

Short description:

Today I'm going to be talking about zero dependency testing with Node.js. Almost all projects need a test runner. Node.js has a good assertion library, reducing dependencies. Many test runners have overlapping functionality. Having a built-in test runner reduces risks and costs. The trend is to include test runners in runtimes. The new test runner in Node supports CLI and standalone file execution. It supports synchronous, promises, async/await, and callback-based tests. Different test runner styles are supported.

Hi everyone! Thanks for coming to my talk. Today I'm going to be talking about zero dependency testing with Node.js, which essentially means that you can start writing your unit tests, integration tests, without having to install anything from NPM.

So before getting into the the nature of Node's new test runner, I wanted to talk a little bit about why a test runner was desired in the first place. So almost all projects need a test runner. So whether you're building an application or a module that you're planning to publish on NPM or whatever, if you're planning to have other people use your code, you almost certainly need tests for it. And then Node.js for years now has shipped with a really good assertion library that's just import assert. This is the assertion library that I've been using for years now. I like it, so that's one less dependency.

And then most test runners overlap a lot in terms of functionality anyway. So, you know, every test runner runs some tests. They generally have features like timeouts, you know, reporting which tests passed and failed, skipping tests, things like that. So, you know, there are differences, so some test runners are more suited to front-end development, some do things like injecting globals into your code without your knowledge, some execute their tests inside of different contexts, so, you might have surprising results whenever you check for equality and things like that. But, you know, so there are these rough edges, but in general, a lot of test runners have a lot of overlap.

And then on top of that, NPM is just really a dangerous place. There's, you know, over the years, there's been a number of incidents, things like left pad, the colors JS thing, even more recently, the minimist package, which I think has like 50 million downloads or something like that, nothing happened to it on NPM, but the GitHub repository went away. So, all of these third party dependencies that you're taking on come with some risk and some cost. And so, that's just, you know, one reason why having a test runner built in, I feel, is useful. And also, there's just a general trend to have more of these batteries included in the runtimes. So, you know, now Node has a built-in test runner. I'm pretty sure Bun has one, I know Deno has one. So, this is becoming more and more common.

And then, you know, here's my tweet from over a year ago, I believe that Node should ship a test runner and, you know, I feel pretty strongly about that. So, some of the features in the new test runner, you can run the test runner through the CLI interface that has the Node chips now with the dash dash test flag. Or you can actually just execute a standalone file containing tests. So, say you have your file foo.js, you can say Node foo.js and if you're using the test runner in there, it will still just work. When it comes to actually writing tests themselves, there's, you know, we support synchronous code, promises or async await based code. And even, you know, because Node still does have a lot of callback-based APIs, we support callback-based tests as well. If you're coming from a test runner like tap or tape, then we do support test style tests, using the test function. If you're coming from a test runner like Mocha or Jest, we have describe and IT functions. So, under the hood, everything uses test, describe and IT are just kind of implemented on top of test.

2. Writing Tests with Node.js

Short description:

If you're looking for that familiar API, it is there. We support nesting tests, skipping tests, and filtering tests by name. Writing a test is simple with Node's assert and test modules. The test runner is published on NPM and supports Node 14, 16, and 18. After executing tests, the output follows the test anything protocol (tap).

But, you know, if you're looking for that familiar API, it is there. We support nesting tests, so you can have, you know, a test with arbitrarily nested tests inside of it. Same if you have describe. You can have suites containing more suites and more tests and things like that.

Skip and to do tests. So, you know, if you just want to skip over a test, there's a few different ways that you can do that. To do is kind of similar to skip in the fact that it won't cause your test suite to fail. But it will still execute the test and kind of don't care about the result. We also have only tests. So if you start the CLI runner with dash dash test only, then any test that you have annotated as being only tests are the only ones that will be executed. And then you can also filter tests by the name of the test. So if you use the dash dash test name pattern, you can actually pass in a regular expression and node will only execute the test whose names match that pattern.

So if you wanted to actually write a test, what would it look like? Here's a very simple example using nothing but node's assert module and node's test module. Here we have two tests. One is a synchronous test that passes and the other is an asynchronous test which fails. The asynchronous test will, even though it looks like synchronous code, it's an async function so it returns a promise. That promise rejects whenever the assertion fails. So two things worth noting here is you'll see here we're using node colon test. The node colon prefix can be used to import any node core module. But starting with the test module and likely with all modules added to node core moving forward, you have to use the node colon prefix. If you just try to use the word test here, it would actually fall back to trying to load from user land. And speaking of user land, the test runner itself is actually published on NPM. So right now the test runner exists in node 18 and 16. Node 14 is still supported, though. So a few people took the code from node core, kind of ported it to work in an NPM module, and published it. So you can just NPM install test if you're on node 14, and you'll still have access to all this functionality. So after you execute your test, this is what the output will look like. So this output is called tap, which stands for test anything protocol. And it's not the most easy for humans to parse, but you can do interesting things like, you know, pipe it into a different reporters and things like that, and have it formatted differently. But you can see here that we have okay 1, that's the first test, that was the synchronous passing test.

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

Scaling Up with Remix and Micro Frontends
Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
This talk discusses the usage of Microfrontends in Remix and introduces the Tiny Frontend library. Kazoo, a used car buying platform, follows a domain-driven design approach and encountered issues with granular slicing. Tiny Frontend aims to solve the slicing problem and promotes type safety and compatibility of shared dependencies. The speaker demonstrates how Tiny Frontend works with server-side rendering and how Remix can consume and update components without redeploying the app. The talk also explores the usage of micro frontends and the future support for Webpack Module Federation in Remix.
Network Requests with Cypress
TestJS Summit 2021TestJS Summit 2021
33 min
Network Requests with Cypress
Top Content
Cecilia Martinez, a technical account manager at Cypress, discusses network requests in Cypress and demonstrates commands like cydot request and SCI.INTERCEPT. She also explains dynamic matching and aliasing, network stubbing, and the pros and cons of using real server responses versus stubbing. The talk covers logging request responses, testing front-end and backend API, handling list length and DOM traversal, lazy loading, and provides resources for beginners to learn Cypress.
Testing Pyramid Makes Little Sense, What We Can Use Instead
TestJS Summit 2021TestJS Summit 2021
38 min
Testing Pyramid Makes Little Sense, What We Can Use Instead
Top Content
Featured Video
Gleb Bahmutov
Roman Sandler
2 authors
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.
Full Stack Components
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
RemixConf EU discussed full stack components and their benefits, such as marrying the backend and UI in the same file. The talk demonstrated the implementation of a combo box with search functionality using Remix and the Downshift library. It also highlighted the ease of creating resource routes in Remix and the importance of code organization and maintainability in full stack components. The speaker expressed gratitude towards the audience and discussed the future of Remix, including its acquisition by Shopify and the potential for collaboration with Hydrogen.
Debugging JS
React Summit 2023React Summit 2023
24 min
Debugging JS
Top Content
Watch video: Debugging JS
Debugging JavaScript is a crucial skill that is often overlooked in the industry. It is important to understand the problem, reproduce the issue, and identify the root cause. Having a variety of debugging tools and techniques, such as console methods and graphical debuggers, is beneficial. Replay is a time-traveling debugger for JavaScript that allows users to record and inspect bugs. It works with Redux, plain React, and even minified code with the help of source maps.
Making JavaScript on WebAssembly Fast
JSNation Live 2021JSNation Live 2021
29 min
Making JavaScript on WebAssembly Fast
Top Content
WebAssembly enables optimizing JavaScript performance for different environments by deploying the JavaScript engine as a portable WebAssembly module. By making JavaScript on WebAssembly fast, instances can be created for each request, reducing latency and security risks. Initialization and runtime phases can be improved with tools like Wiser and snapshotting, resulting in faster startup times. Optimizing JavaScript performance in WebAssembly can be achieved through techniques like ahead-of-time compilation and inline caching. WebAssembly usage is growing outside the web, offering benefits like isolation and portability. Build sizes and snapshotting in WebAssembly depend on the application, and more information can be found on the Mozilla Hacks website and Bike Reliance site.

Workshops on related topic

Designing Effective Tests With React Testing Library
React Summit 2023React Summit 2023
151 min
Designing Effective Tests With React Testing Library
Top Content
Featured Workshop
Josh Justice
Josh Justice
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
Master JavaScript Patterns
JSNation 2024JSNation 2024
145 min
Master JavaScript Patterns
Featured Workshop
Adrian Hajdin
Adrian Hajdin
During this workshop, participants will review the essential JavaScript patterns that every developer should know. Through hands-on exercises, real-world examples, and interactive discussions, attendees will deepen their understanding of best practices for organizing code, solving common challenges, and designing scalable architectures. By the end of the workshop, participants will gain newfound confidence in their ability to write high-quality JavaScript code that stands the test of time.
Points Covered:
1. Introduction to JavaScript Patterns2. Foundational Patterns3. Object Creation Patterns4. Behavioral Patterns5. Architectural Patterns6. Hands-On Exercises and Case Studies
How It Will Help Developers:
- Gain a deep understanding of JavaScript patterns and their applications in real-world scenarios- Learn best practices for organizing code, solving common challenges, and designing scalable architectures- Enhance problem-solving skills and code readability- Improve collaboration and communication within development teams- Accelerate career growth and opportunities for advancement in the software industry
How to Start With Cypress
TestJS Summit 2022TestJS Summit 2022
146 min
How to Start With Cypress
Featured WorkshopFree
Filip Hric
Filip Hric
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.
Integrating LangChain with JavaScript for Web Developers
React Summit 2024React Summit 2024
92 min
Integrating LangChain with JavaScript for Web Developers
Featured Workshop
Vivek Nayyar
Vivek Nayyar
Dive into the world of AI with our interactive workshop designed specifically for web developers. "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" offers a unique opportunity to bridge the gap between AI and web development. Despite the prominence of Python in AI development, the vast potential of JavaScript remains largely untapped. This workshop aims to change that.Throughout this hands-on session, participants will learn how to leverage LangChain—a tool designed to make large language models more accessible and useful—to build dynamic AI agents directly within JavaScript environments. This approach opens up new possibilities for enhancing web applications with intelligent features, from automated customer support to content generation and beyond.We'll start with the basics of LangChain and AI models, ensuring a solid foundation even for those new to AI. From there, we'll dive into practical exercises that demonstrate how to integrate these technologies into real-world JavaScript projects. Participants will work through examples, facing and overcoming the challenges of making AI work seamlessly on the web.This workshop is more than just a learning experience; it's a chance to be at the forefront of an emerging field. By the end, attendees will not only have gained valuable skills but also created AI-enhanced features they can take back to their projects or workplaces.Whether you're a seasoned web developer curious about AI or looking to expand your skillset into new and exciting areas, "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" is your gateway to the future of web development. Join us to unlock the potential of AI in your web projects, making them smarter, more interactive, and more engaging for users.
Detox 101: How to write stable end-to-end tests for your React Native application
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
Yevheniia Hlovatska
Yevheniia Hlovatska
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
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
React Day Berlin 2022React Day Berlin 2022
86 min
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
Top Content
WorkshopFree
Hussien Khayoon
Kahvi Patel
2 authors
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.