Saturday, February 20, 2021

Adding Jest to project

Hello dear developer,

Would you like to have peace of mind that your work is not buggy, impress your boss with state of art technology and be more productive? Then a Unit Testing is for you!

And what better place to implement it other than your project? 

The first question is how do we start. Afterall, there are so many frameworks out there: Cypress, Mocha, puppeteer, ... For this example we'll go with the most popular one in 2020: Jest.

Don't be fooled by its name. According to their website it's a "delightful JavaScript Testing Framework with a focus on simplicity", which I'll agree with.

The first thing we need is to install some dev dependencies (--save-dev) on your root package.json.

We'll need "jest", for obvious reasons.

npm i jest --save-dev

If we are using ES6 or ES7 (which we'll likely do), then we'll need a library to convert the js code into something that Jest can read. For that we'll also need to install "babel-jest" and "@babel/plugin-transform-modules-commonjs". 

npm i babel-jest--save-dev
npm i @babel/plugin-transform-modules-commonjs--save-dev

Then we need to add 2 new files.

- jest.config.js. In here will be all the jest configurations, like where to look for the unit test files (in the example, on a __tests__ folder with a file ending with .spec.js), where not (node_modules) and where to apply the babel-commonjs (all js files). Here's an example:

module.exports = {
    rootDir: "./",
    moduleFileExtensions: ["js", "jsx"],
    testPathIgnorePatterns: ["/node_modules/", "/public/"],
    transform: {
        "^.+\\.(js)$": "./node_modules/babel-jest"
    },
    testRegex: ".*/__tests__/.*\.spec.js$"
};

- babel.config.js. Here will be present the babel configuration. For this example we only need to specify that our code may contain the latest JS standards, so we'll need @babel/preset-env.


module.exports = {
    presets: ["@babel/preset-env"],
};

Finally, on package.json, we can add/update a "test" script to use jest, like this:


"scripts": {
    "test": "jest -c ./jest.config.js"
},

Now to run the unit test, we just need to type "npm run test" and if everything goes well, we've got all units tests running on your terminal.

No comments:

Post a Comment