Testing Code

Testing Code

Why Test

Everything we write should be tested. When I grade your code I’m really testing it to make sure it does what its is supposed to do.

When you write a test, you are able to make sure say what your code it doing. So if you make a change to the code that you have a test for, you are sure that it will still do the things that it is supposed to do.

How to test

Every language has its own testing tools for JavaScript jest is a regularly used one.

Setup First

npm install --save-dev jest

This will add the Jest library to the application so we can use it to run tests.

Add a new script to your package.json file


  "scripts": {
    "start": "node ./bin/www",
    "dev": "nodemon ./bin/www --ignore sessions",
    "refresh": "node migrate",
    "test": "jest"
  },

Run test

npm test

Write the test first

mkdir test
touch sum.test.js

```JS
const sum = require('../sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});~

Then write the code to pass the test

function sum(a,b) {
  return 3;
}

module.exports = sum;

Lets update it to make it better

function sum(a,b) {
  return a+b;
}

module.exports = sum;

Update for linter

/* eslint-disable no-undef */