Kaigai Blog living abroad in my twenties

【My Study Note】Writing Tests with Jest

JavaScript Programming

Writing Tests with Jest

This is the function that we would test

// addFive.js
function addFive(val){
    return val + 5;
}
// Export the function
module.exports = addFive;

But before switching over to using the jest testing framework to write some expectations of how this function should behave, you should do few things.

1. Is NodeJS. installed on your system?

// In the terminal, type below
node --version

2. Is NPM installed on your system?

// In the terminal, type below
npm --version

3. Add package.json file

// In the terminal, type below
npm init -y

After that, you would have your package.json file. In other words, you have a way to keep track of node modules that this project depends on.

4. Install Jest

// In the terminal, type below
npm install --save -dev jest

After a few moments, the package.json file will be updated with the addition of the jest testing library. You also have a folder called node_modules, which is where the code for all the modules in this project is stored.

5. Change few things script section of package.json file

{
  "name": "try",
  "version": "1.0.0",
  "description": "",
  "main": "addfive.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "jest": "^29.3.1"
  }
}

You replace the text that is assigned to test which is “echo \”Error: no test specified\” && exit 1″ with “jest” and save it. Now when you run the command NPM run test, it will run the Jest command in this folder.

// This is how it would be
% npm run test

> try@1.0.0 test
> jest

 

6. Create a test file

For example, like this “addFive.test.js”. You add the dot test before the dot js.

7. Set the test file

// addFive.test.js
const {default: TestRunner} = require("jest-runner");
const addFive = require('./addFive');
// Importing "addFive.js" file. ()

test('test returns the number plus 5', ()=> {
    expect(addFive(1)).toBe(6);
    // You are testing the addFive funciton from the addFive.js file
})

The reason for the forward slash is to indicate that the function is in the same folder as a test file, and you can also omit the dot js because Node understands what you mean, even if you don’t use it.

8. You can test by typing… in terminal

npm run test

9. The result would be like this

> try@1.0.0 test
> jest

 PASS  ./addFive.test.js
  ✓ test returns the number plus 5 (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.302 s, estimated 1 s
Ran all test suites.