Jest for Unit Testing
Install Jest
npm install --save-dev jest
You may get some dependency warnings for the following packages - canvas, bufferutil, and utf-8-validate. If so use the following commands to install the updates
npm install --global canvas
npm install --global bufferutil
npm install --global utf-8-validate
Add the following json to the package.json file
{
"scripts": {
"test": "jest"
}
}
Creating a test
Jest tests should be in a subfolder called _test_ of the from where package.json is located. If you want to use a folder with a different name - see below.
Each test file should be prefixed with either test.js or spec.js e.g. maths.test.js.
The jest test file cannot use TypeScript but the CUT (Class Under Test) may be written using TypeScript - see below.
maths.test.js
Create the CUT
maths.ts
Now run the test using
Because we are using TypeScript you will see the following error
The failure is because Jest does not directly support TypeScript. Babel must be installed using yarn.
Begin by install yarn via npm
Setting up Babel
Configure Babel to target your current version of Node by creating a babel.config.js
Install babel dependencies via yarn
Enabling TypeScipt
Install the @babel/preset-typescript
via yarn
:
Now modify the babel.config.js so that it looks like this
Configuring file structures
Add a file called jest.config.js to the root of the project
Dependencies errors
The most common errors I have found are
I have found that by rerunning these two commands the problems are resolved
You should now be able to test TypeSctipt files.