Member-only story
Using Jest Mocks + TypeScript the Right Way
Write better unit tests

Note: This article assumes a basic understanding of Jest and the React Testing Library. If you are not familiar with the general testing structure of React, I recommend starting with this series.
Mocking is a core tenet of unit-testing a React application. It is a key tool for following RTL’s best practice of not testing implementation details, as well as the fundamental idea of isolation in all unit testing.
The Jest documentation covers an assortment of methods for mocking and several very helpful use cases. But what it’s missing is a basic overview of what you are doing when mocking something. I find this imperative to successfully applying the methods that they outline to your own application.
Alas, we have our topic for the day: How do you properly mock what you need for a production React application? We will discuss mocking on a philosophical level and walk through basic mocks of a local Config
file as well as Auth0’s React SDK.
I chose the Auth0 SDK because it has very specific use cases intended to be run in a browser and is also often central to what you want to test in your code. In other words, it is a perfect use case for something that needs mocking and needs to be mocked properly in order to test.

What Does Unit Testing Achieve?
The goal of unit testing is to confirm that a block of code written by you (or someone on your team) works as expected. That is it.
Unit testing is not intended to and should not test whether functions and modules imported from third-party dependencies are working or the status of an API from which the code fetches — or anything browser-specific, such as network or security concerns.
In order to properly unit-test, we need to isolate the unit of code being tested from all of these other concerns. This allows us to confidently assert on the result of our code block.