Set up Jest in your Monorepo in 5 minutes

Kyle Le
Level Up Coding
Published in
3 min readOct 24, 2022

--

Introduction

Jest is a delightful JavaScript Testing Framework with a focus on simplicity. And you can use Jest on everything that is JavaScript like React, Angular, Node, TypeScript…

I have a tutorial about setting up Jest for your project here

And a Monorepo or Monorepository is a code management and architectural concept where you keep all your code in one super repository instead of managing multiple smaller repositories — like a single repository for your website and libraries

I also have a tutorial on how to create a package-based Monorepo with NX right here

Setup Jest

This article will be a tutorial on how to set up Jest for your Monorepo, start with installing Jest and TS-jest on your root folder:

yarn add jest @types/jest ts-jest

Config Jest

After all dependencies installed, we initialize the jest config file with typescript supported:

yarn ts-jest config:init

The jest.config.js file will be created. We’re going to do all the configurations here, but first, let’s see my packages:

I have 2 packages: common-ui and web , here is the jest.config.js

I will go from top to bottom:

  • preset : obviously ts-jest
  • testEnvironment : we gonna use jsdom so we can do document methods in our tests
  • rootDir : since this is a monorepo, we might want to have a rootDir constant for readability
  • coverageDirectory : the folder we want put our code coverage reports
  • collectCoverageFrom : as you can see, I only want to collect .ts files and exclude constant.ts and index.ts ( you can easily customize this based on your needs )
  • projects : This is the most important part, we are going to set up Jest specifically for each of our package.
  • testMatch : we match the test with its .spec.ts counterpart to correctly collect its coverage.

Running Tests

We can run Jest right at the root folder with yarn jest

Conclusion

This is a simple tutorial on how to config Jest for your Monorepo with my jest.config.js sample. Just config Jest based on your monorepo and liking

Last Words

Although my content is free for everyone, but if you find this article helpful, you can buy me a coffee here

Level Up Coding

Thanks for being a part of our community! Before you go:

🚀👉 Join the Level Up talent collective and find an amazing job

--

--

I’m a Software Engineer who loves to write. My content is based on what I've learned and experienced every day