How to use jest with Nodejs ES modules to test express controllers. Here you will find how to test asynchronous code and how to use mocks to get rid of side effects.
Note: Babel is used to enable Jest using with ES6 modules.
To go through it on your own:
-
Initialize your app
npm init
-
To use ES modules, add
type: "module"
topackage.json
file. -
Install express, mongoose and jest packages
npm install express mongoose jest
-
Initialize jest
npm init jest@latest
-
In
jest.config.mjs
file: de-commenttransform
key and assign it a value liketransform: { "^.+\\.js$": "babel-jest" }
. Just be aware that therejex
will depend on the file extensions on your project. -
Install babel
npm i @babel/core @babel/node @babel/preset-env
-
Configure babel by creating
.babelrc
file in the root folder. -
Inside
.babelrc
file write{ "presets": [["@babel/preset-env", { "targets": { "node": "current" } }]] }
If you have no background in testing, check out this tutorial:
https://www.freecodecamp.org/news/how-to-handle-side-effects-in-jest/