hilton meyer

Adding Jest for testing

This is a quick and simple way to get Jest up and running in a project. This can either be done by adding it at the beginning of a project and then doing TDD development which is something I will be looking at in the upcoming weeks. The option is to add this to an existing application and then add tests to new code or write retroactive tests. So first step is to install Jest and supertest, supertest is what I use for testing http endpoints and seeing as I'm doing quite a bit of development using Netlify Functions so I use this to test those API's.

npm install --save-dev jest supertest

Add the following section to your package.json to create a script for running your tests. I use the watchAll parameter to be able to not have to restart the tests continually. This means that as I write the tests or develop my application the tests run and tell me if something is not working. Basically I get a heads up if I break something somewhere else in my code by using previous tests. The other advantage is that I can then write the tests and start working on the solution in my code base. This cycle can just continue and I have someone looking at my code all the time throwing up a flag if something isn't quite kosher.

{
  "scripts": {
    "test": "jest --watchAll"
  }
}

Config jest to be setup for node by setting up a jest.config.js file and adding the following. This will setup the environment for node and also exclude any node_modules from being included in the tests. Very basic setup, I am developing in Node for my Netlify functions so I use that as my environment. This is not required as out of the box Jest works.

module.exports = {
  verbose: true,
  testEnvironment: 'node',
  coveragePathIgnorePatterns: ['/node_modules/'],
};