jest - GradedJestRisk/js-training GitHub Wiki

Table of Contents

Reference

List:

Install

Is it right to install jest globally ? Anyway, if using vscode, add jest extension.

Start a project with Jest

Init project

Steps:

  • create a directory mkdir PROJECT_NAME
  • init project npm init --y
  • install jest:
    • global (evil):
      • install npm install jest --global
      • set up jest jest --init
    • local: npm install --save-dev jest
  • commit
  • if using vscode :
    • open folder and create a workspace
    • make sur jest extension is alive (bottom bar)

Add SUT

Add file sum.js

function sum(a, b) {
  return a + b;
}
module.exports = sum;

write test

Add file sum.test.js

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

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

execute test

Launch tests:

  • in command-line:
    • all tests: npm run test
    • one test: npx jest <FILE-PATH>
  • if using vscode, click on Jest on btton bar
You will get
> jest

 PASS  ./sum.test.js
  √ adds 1 + 2 to equal 3 (3ms)

try TDD

If using vscode with Jest extension, add a new test

test('adds 1 + A to be 1', () => {
  expect(sum(1, 'A')).toBe(3);
});

It should fail, you should get a red dot on the left of the test's name.
When you change the test/code to get a correct expectation, the test may remain red.
Fire it forcefully by saving file (Ctrl+ S).

Write tests

describe

describe is a function whose parameters are:

  • a string, the test suite description, eg: "functional programming syntax "
  • an anonymous function, that contains test cases functions

test is a function whose parameters are:
  • a string, the test description, eg: "reduce() applies an operator on all elements"
  • an arrow function, that contains an expect method

expect is a function :
  • whose parameter is an expression.
  • that returns an object ?

toBe is a function on object :

  • whose parameter is an expression.
  • that returns true if the expression evaluated on object is true

test

setUp and tearDown

expectations

check success manually

You check it using vanilla JS, then fail in case. Use fail('I shoulnd't be there..');

expect errors

test('throws on octopus', () => {

  function drinkOctopus() {
    drinkFlavor('octopus');
  }

  expect(drinkOctopus).toThrowError(new Error('yuck, octopus flavor'));

});

more here

TDD in vscode

requires

Extensions:

baby steps

Overview:

  • create suite with desc
  • create test with test
  • code your first failing test
  • make your first code pass
  • (stuck in red light ? discard all changes Shift Ctrl S)
  • stage/commit with Control S
  • refactor
  • stage/commit with Control S
You can also skip git automator and stage/commit with
  • stage (all) changes: Control Shift A
  • get focus on commit zone: Ctrl 0
  • enter commit comment and save: Ctrl S

Mocking

⚠️ **GitHub.com Fallback** ⚠️