Reader small image

You're reading from  Accelerating Server-Side Development with Fastify

Product typeBook
Published inJun 2023
Reading LevelBeginner
PublisherPackt
ISBN-139781800563582
Edition1st Edition
Languages
Tools
Right arrow
Authors (3):
Manuel Spigolon
Manuel Spigolon
author image
Manuel Spigolon

Manuel Spigolon is a Senior Backend Developer at Near Form. He is one of core maintainers on the Fastiy team. Manuel has developed and maintained a complex API that serves more than 10 millions world wide.
Read more about Manuel Spigolon

Maksim Sinik
Maksim Sinik
author image
Maksim Sinik

Maksim Sinik is a senior engineering manager and a core maintainer of the Fastify framework. He has a decade of experience as a Node.js developer with a strong interest in backend scalability. He designed the architecture and led the development of several service-based Software-as-a-Service (SaaS) platforms across multiple industries that process hundreds of thousands of requests.
Read more about Maksim Sinik

Matteo Collina
Matteo Collina
author image
Matteo Collina

Matteo Collina is the co-founder and CTO of Platformatic who has the goal of removing all friction from backend development. He is also a prolific open source author in the JavaScript ecosystem, and the modules he maintains are downloaded more than 17 billion times a year. Previously, he was the chief software architect at NearForm, the best professional services company in the JavaScript ecosystem. In 2014, he defended his Ph.D. thesis titled Application Platforms for the Internet of Things. Matteo is a member of the Node.js Technical Steering Committee, focusing on streams, diagnostics, and HTTP. He is also the author of the fast logger, Pino, and the Fastify web framework. Matteo is a renowned international speaker after more than 60 conferences, including OpenJS World, Node.js Interactive, NodeConf.eu, NodeSummit, JSConf.Asia, WebRebels, and JsDay, to name just a few. Since August 2023, he also serves as a community director on the OpenJS Foundation. In the summer, he loves sailing the Sirocco.
Read more about Matteo Collina

View More author details
Right arrow

Application Testing

Proper testing is a primary, essential aspect that will make an application reliable for years to come. Fastify comes with several integrated tools specifically developed for making the testing experience as slick as possible. This means that writing an application test will not be frustrating and slow to run. Nevertheless, Fastify is test runner-agnostic; it perfectly integrates with the runner of your choice.

In this chapter, you will learn how to use integrated methods and run tests in parallel without having to spin an actual HTTP server.

The learning path we will cover in this chapter is as follows:

  • Writing good tests
  • Testing the Fastify application
  • Dealing with complex tests
  • Speeding up the test suite
  • Where tests should run

Technical requirements

To go through this chapter, you will need the following:

  • A working Node.js 18 installation
  • The VSCode IDE from https://code.visualstudio.com/
  • A Docker installation
  • A public GitHub repository
  • A working command shell

All the snippets in this chapter are on GitHub at https://github.com/PacktPublishing/Accelerating-Server-Side-Development-with-Fastify/tree/main/Chapter%209.

Writing good tests

Implementing tests for an application is an investment to free you up from the stress that a new project could give you. Thanks to these tests, you can be (pretty) sure of implementing new features or fixing bugs without breaking the existing software. Unfortunately, writing tests often gets sacrificed whenever a project is running out of time. This is also an activity that many consider to be boring and frustrating, due to the many blockers you may face by testing an HTTP server, such as the server port already in use. So, the tests are often written quickly and without the required attention.

We can say that an application’s test suite is successful under the following conditions:

  • It’s automated – you just need to click a button to get many hours’ worth of work done
  • It’s easy to maintain – adding a new test must be easy, and it should not take more time than developing the feature itself
  • Running the tests...

Testing the Fastify application

We are ready to implement the tests for our Fastify application. Before we start, we need to choose a framework that will help us write the code. Let’s complete this task first!

Installing the test framework

There are a lot of testing frameworks in the Node.js panorama. Some of them are highly opinionated, and others try to be agnostic. We are not going to discuss comparing the most famous modules. It is worth mentioning the ones most used by the community (in alphabetical order):

The framework we will use is node-tap because it has all the key features out of the box without needing extra configuration, such as the following:

  • An easy-to-use and solid implementation
  • Comprehensive assertions
  • ...

Dealing with complex tests

So far, we have seen simple test cases that did not require multiple API requests. So, let’s create the test/login.test.js file to verify the sign-up and first user login to our application. We will use what we have learned so far, keeping in mind that we don’t want to replicate code.

We need to build the Fastify instance to write new test cases, as we did in the test/basic.test.js file. To do so, we need to do the following:

  1. Create a new utility file and call it test/helper.js.
  2. In the test/helper.js file, move the buildApp function and its configuration variables, startArgs and envParam. This action requires some copying and pasting.
  3. Update the test/basic.test.js file within the new import, const { buildApp } = require('./helper').

By doing so, we can reuse code to instantiate the Fastify application across all the test files we are going to create. We are now ready to write more complex tests.

Reusing...

Speeding up the test suite

There are not many tests in the actual application, but they’re all pretty fast. While your project will grow, the tests will become more and more time-consuming and more annoying to run. It is not uncommon to have a test suite that runs in a span of 15 minutes, but that is too much time! Now, we are going to see how to speed up a test run to avoid a situation like this, by parallelizing the tests’ executions and evaluating the pitfall this technique carries.

Running tests in parallel

To improve our test run, we need to update the test script in package.json:

"test": "tap test/**/**.test.js",

The npm test command will execute all the files in the test/ folder that ends with the test.js suffix. The cool thing is that each file runs in parallel on a dedicated Node.js process! That being said, it hides some considerations you must be aware of when writing tests:

  • process.env is different for every test file...

Where tests should run

Up until now, we have executed our test manually on our PC. That is fine, and it is mandatory during the development phase. However, this is not enough because our installation could be edited, or we could have some uncommitted files.

To solve this issue, it is possible to add a Continuous Integration (CI) pipeline that runs remotely to manage our repository. The CI pipeline’s primary duties are as follows:

  • Running the test suite to check the code in the remote Git repository
  • Building a code base to create artifacts if necessary
  • Releasing the artifacts by triggering a Continuous Delivery (CD) pipeline to deploy the software

The CI workflow will notify us about its status, and if it is in a red state, the application’s tests are failing with the last commit. Running the test remotely will prevent false-positive issues due to our local environment setup.

We will build a simple CI workflow by adopting GitHub Actions. This...

Summary

This chapter is dense with information about new processes and tools. Now, you should be comfortable designing a test suite for a Node.js backend application. You should be able to evaluate a testing framework that fits your needs and boosts your productivity.

You have learned how to use node-tap, from basic assertions to advanced parallel test execution. Moreover, you can test a Fastify application and take advantage of Fastify’s inject feature. You don’t have to worry about testing your API’s routes, whatever the level of complexity is.

Finally, we have seen how to integrate a CI pipeline using GitHub Actions and its logic to keep our repository away from regressions and production issues.

Now, you are ready to proceed to the next step and build a secure and reliable application. We mentioned CD earlier in this chapter; it is now time to see it in action in Chapter 10.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Accelerating Server-Side Development with Fastify
Published in: Jun 2023Publisher: PacktISBN-13: 9781800563582
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (3)

author image
Manuel Spigolon

Manuel Spigolon is a Senior Backend Developer at Near Form. He is one of core maintainers on the Fastiy team. Manuel has developed and maintained a complex API that serves more than 10 millions world wide.
Read more about Manuel Spigolon

author image
Maksim Sinik

Maksim Sinik is a senior engineering manager and a core maintainer of the Fastify framework. He has a decade of experience as a Node.js developer with a strong interest in backend scalability. He designed the architecture and led the development of several service-based Software-as-a-Service (SaaS) platforms across multiple industries that process hundreds of thousands of requests.
Read more about Maksim Sinik

author image
Matteo Collina

Matteo Collina is the co-founder and CTO of Platformatic who has the goal of removing all friction from backend development. He is also a prolific open source author in the JavaScript ecosystem, and the modules he maintains are downloaded more than 17 billion times a year. Previously, he was the chief software architect at NearForm, the best professional services company in the JavaScript ecosystem. In 2014, he defended his Ph.D. thesis titled Application Platforms for the Internet of Things. Matteo is a member of the Node.js Technical Steering Committee, focusing on streams, diagnostics, and HTTP. He is also the author of the fast logger, Pino, and the Fastify web framework. Matteo is a renowned international speaker after more than 60 conferences, including OpenJS World, Node.js Interactive, NodeConf.eu, NodeSummit, JSConf.Asia, WebRebels, and JsDay, to name just a few. Since August 2023, he also serves as a community director on the OpenJS Foundation. In the summer, he loves sailing the Sirocco.
Read more about Matteo Collina