tristin

Table driven tests in Go aren’t new, but I haven’t seen something similar in JavaScript code bases I’ve worked in.

Behold a table driven test in Node.

// The function under test
function add1(number) {
if (number > 99) {
throw `I can't count that high!`
}
return 1 + number;
}
// The tests
Object.entries({
'adds 1 to a small number': {
number: 9,
expectedOut: 10,
},
'throws an error for big numbers': {
number: 100,
expectedErr: `I can't count that high!`,
},
}).forEach(([name, t]) => {
it(name, () => {
if (t.expectedErr) {
expect(add1(t.number)).toThrow(t.expectedErr);
} else {
expect(add1(t.number)).toEqual(t.expectedOut);
}
});
});

Just a thought.

tristin

tristin

software engineer, futures enthusiast, and aspiring farmer.