DEV Community

Cover image for TAWIL: How to write tests with Jest 🃏
Javel Rowe
Javel Rowe

Posted on

TAWIL: How to write tests with Jest 🃏

Hello world. Today at work I learnt how to do the above. It's never too late to begin increasing your confidence in your code. In four steps, we'll have a small testing suite up and running. Let's start!

Step 1 - Dependencies

These 3 steps should be similar for all editors from VS Code to Notepad.

  • Check that you have Node.js installed by running node -v in your terminal. You should see something like this:
v14.9.0
Enter fullscreen mode Exit fullscreen mode
  • CD to a folder of your choice (even Desktop, I won't judge), then run npm init then npm i jest --save-dev

  • Finally, in the package.json file that appeared out of nowhere, add jest --verbose under scripts in the key titled 'test' like so:
    edit-pkg_json

Step 2 - Functions to test

Let us create a file titled countr.js. In it, we shall write a set of functions for a counter app. The functions will accept a number as an argument then increase or decrease its value by 1.

const increase = (a) => ++a;
const decrease = (b) => --b;

module.exports = { increase, decrease };
Enter fullscreen mode Exit fullscreen mode

Step 3 - A test for our functions

Now we shall write some tests! In the same directory, create a file titled countr.test.js. In here, add the following bit of code:

const { increase, decrease } = require('./countr');

test('Increaase yah noww', () => {
  expect(increase(3)).toBe(4);
});

test('Beg yuh one nuh', () => {
  expect(decrease(4)).toBe(3);
});

Enter fullscreen mode Exit fullscreen mode
Teching Things Apart

This expect(increase(2)).toBe(3) bit of code does the actual work for us. The expect() function accepts as an input the value that our code ( increase(3) ) outputs. The toBe() matcher function accepts the value we hope our code will output.

Step 4 - Testing 123..

Finally, in your terminal, run the command npm test anddd 🥁 🥁 🥁 🥁
You should see these beautiful messages appear before your very eyes:
Screenshot 2021-02-03 at 7.03.37 PM

That's it! Welcome to the club!

Attributions

Header - Design vector created by macrovector - www.freepik.com

Top comments (0)