React Native

Nock vs MSW: I tested both and here is what I learned

How did I end up comparing Nock and MSW? 🤔

It all started when I launched a new React Native project. I spent a lot of time setting up a slick design system, configuring eslint, making sure TypeScript was running smoothly and adding Jest & React Testing Library for a robust testing. Yet as I was enjoying my well-organized app, I was faced with an enormous decision to make: Which mocking library should I use for my tests?

I started to panic, so I asked for advice around me. But I hit a wall, some told me that Nock was the answer to all my problems, others that I should not hesitate one more second and take MSW. I was stuck, Nock? MSW? The more I thought about it, the more I realized I needed to dive in and figure out which one would help me tame the wild beast of testing.

So, armed with a dose of curiosity and the desire to find the truth, I set out on my quest to find the ideal mocking library. My goal? To make my testing life easier and to help others who might face the same tricky decision in their own projects.

Introduction of the participants 🏆

Welcome to the mocking library arena! Today we have two formidable opponents ready to compete for the title of HTTP mocking champion.

First, we'll introduce our first entrant:

MSW 🥊 , aka Mock Service Worker. This elegant and versatile HTTP mocking library is reminiscent of Express in its design, making simulation setup fun and intuitive. MSW is ready to fight on many fronts, running smoothly in environments like Node, React Native and your browser. By operating directly at the network level, MSW avoids the need for additional adapters for your fetching libraries.

Now, let's move on to Nock 🐱👤, the strong opponent in this battle. Nock is a fast and easy to set up HTTP mocking library that is easy to understand and use. With extensive documentation, Nock also has additional functionality, including the famous "Recorder" that records incoming requests and automatically generates the simulations you need. However, Nock sometimes has to rely on additional adapters for certain recovery libraries, such as Axios.

Which of these two competitors will win the mocking library battle? The final choice will of course depend on your specific needs and preferences. May the best one win!

The comparison criteria 🌡

In this arena, Nock and MSW will be judged on several crucial criteria to determine which one will be crowned the champion of HTTP mocking libraries. These criteria include:

Ease of use: An effective fighter should be easy to grasp and master. We want to know which of these libraries makes creating mocks quick and easy.

Control over item matching: Accuracy is paramount in a fight. We will check how easy these libraries are to create complex matches for mocks.

Speed: In the arena, speed is essential. We will evaluate how these libraries affect test performance.

Memory consumption: Lightweight is a major advantage for a competitor. We will compare the memory consumption of the two libraries.

Compatibility: A true champion must be able to adapt to different situations. We will examine the compatibility of these libraries with various fetching technologies.

Versatility: Finally, a champion must excel in a variety of situations and with different technologies. We will analyze the ability of these libraries to work in environments such as Node, the browser, React Native, and with APIs such as GraphQL and REST.

These criteria are essential to evaluate the strengths and weaknesses of our two competitors, MSW and Nock. So stay tuned and be ready to see these libraries battle for supremacy in this unforgiving arena!

Results and comparative analysis 📊

We will now analyze the capabilities of MSW and Nock by examining their performance on the previous criteria. To spice things up, we'll highlight some code differences between the two fighters when the scores diverge. Scores are given on a scale of 0 to 5. Get ready for the fight!

😌 Ease of use:

Nock: 5

MSW: 3.5

Nock is slightly easier to use than MSW because its setup is very fast, we just need to import the library and then we can create our first mock with a minimum of necessary lines, this is a big benefit of the method chaining.

For example, here is how to setup a mock with Nock in a test :

For MSW, it's more challenging as it requires initial setup and you’ll need your server reference for the addition of new handlers. However, once inside the handler, it resembles the Express backend framework. There's a sense of complete control over requests and results without necessarily needing to consult documentation for all functions.

🚔 Control over item matching:

Nock: 5

MSW: 4

Both libraries offer excellent control over element matching, allowing complex and accurate configurations for your simulations. However you will need additional setup in MSW while Nock offers ready to roll matching functionalities. That’s why MSW lost a point here.

🏎 Speed and 💽 Memory consumption:

Nock: 5

MSW: 5

Both libraries perform well and do not slow down your tests, providing a fast and efficient testing experience. They also have similar memory consumption, which means they will not negatively impact your overall system performance.

To get these results, I tested both libraries speed and memory on 2 project :

MSW is a bit faster and uses less memory on a little project but seems to be working a bit slower on a bigger project. However those minor differences can come from your libraries and handlers configurations.

🤼‍♂️ Compatibility on the Node environment:

Nock : 3

MSW : 5

MSW has the advantage in compatibility, because it works directly at the network level and does not need additional adapters for different fetching libraries. On the contrary, Nock acts right before the network layer, so it requires an adapter to work for some libraries like Axios, which explains the difference in score.

MSW can do this because it operates directly on the network layer, here is an example of how it does it on Node:

Modified from https://mswjs.io/docs/#request-flow-diagram

Tips 🙌 : If you want to use Axios with Nock, you should add these lines to your project to change the default adapter of Axios for one supported by Nock

🤹‍♀️ Versatility:

Nock: 3

MSW: 5

MSW again shines in this category, offering support for a variety of environments such as Node, the browser, React Native, and APIs like GraphQL and REST. Nock, on the other hand, is less versatile and is only working on a Node or React Native environment with a REST api

Sooo… should I use Nock or MSW on my project ? 🤔

🕰 Recap:

Here is a condensed version of the results :

As you can imagine, the choice between Nock and MSW really depends on the specific requirements and constraints of your project. Here are several situations to help you decide which one to choose:

Multi-environment compatibility: If you need an HTTP mocking library that works smoothly in different environments such as Node, browsers, and React Native, MSW would be the best choice. This is because it is designed to work at the network level and offers broader compatibility. It's a bit like choosing between a car that only drives on the highway and one that can also take the back roads!

Existing codebase: If you are working on an existing project that already uses Nock and the current configuration meets your needs, there may be no compelling reason to switch to MSW. However, if you encounter limitations with Nock, especially when using different recovery libraries, you might consider migrating to MSW.

Testing philosophy: If you follow a strict testing philosophy that aims to test your code the same way it runs in production, you may prefer MSW, as it simulates real network requests more closely.

Creating a small project: If your project is going to be limited to a few tests and your goal is to be as fast as possible, then it is better to use Nock with its fast setup and pre-built matching features.

If you ask me, my top choice on most of my projects is MSW because I feel like I have more control over it, and it is easier to come with your own logic. So if, like me, you like to understand everything that’s happening in your mock, I would highly recommend it !

Beyond the Battle: Mastering Mocking Wrappers 👨‍🎓

After this epic battle between the two titans of HTTP mocking, you now know a lot more about Nock and MSW and their use. However, new questions arise:

  • What if a new fetching library appears and you want to switch to it?
  • How to handle complex matching or set up efficient debugging for all your mocks?

Well, fear not, because the solution lies in the use of a "Wrapper" that will allow you to abstract the mocking logic and easily adapt to future changes.

To stay updated on how to create and use a Wrapper and get the most out of HTTP mocking libraries, be sure to follow me on Twitter. And so, no matter which champion you choose in the battle between Nock and MSW.

If you're looking to ace your tests, don't miss this article that will help you understand the key differences between getBy, findBy, and queryBy.

Développeur mobile ?

Rejoins nos équipes