ToDo or Die — Learning TDD

What is software testing?

What is TDD (Test-Driven Development)?

The 3-step process of TDD

  1. Write a test, watch it fail
  2. Write code to make the test pass
  3. Refactor the code
3-step process of TDD — Image credit dywl

How to do TDD

Prerequisite

Project requirement

// Addition in javascript2 + 2 = 4;2 + “2” = 22; // oh oh!

Getting started


“scripts”: {
“test”: “mocha”
}

Write a test that fails


const chai = require(‘chai’);
describe(‘#add’, () => {
it(‘should add two numbers correctly’, () => {
expect(add(2, 2)).to.equal(4);
});
});
failing test

Write code to pass the test


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

const chai = require(‘chai’);
const add = require(‘../addition’);
describe(‘#add’, () => {
it(‘should add two numbers together correctly’, () => {
expect(add(2, 2)).to.equal(4);
});
it(‘should throw error for invalid argument’, () => {
expect(() => add(‘4’, 2)).to.throw(‘Invalid argument’);
});
});
test passes

Refactor


function add (a, b) {
if (typeof a !== ‘number’ || typeof b !== ‘number’) throw new TypeError(‘invalid argument’);

return a + b;
}
module.exports = add;
all test passess

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store