Unit Tests

In this lesson, we'll learn what Unit Tests are and how to build and run them.

We'll cover the following...

Unit tests should be straightforward and answer, “given these inputs, what are the expected outputs.”

Press + to interact
function runner({inputs, expectedOutputs, func}) {
assert(inputs.length === expectedOutputs.length);
for (let i = 0; i < inputs.length; i++) {
assert(func(inputs[i]) === expectedOutputs[i]);
}
}
function firstNameTest() {
const invalidInputs = ["@", "", "blah$", "123"];
const validInputs = ["asdf", "Alfred", "ALFRED"];
runner({
inputs: validInputs,
expectedOutputs: validInputs.map(_ => true),
func: isValidName
});
runner({
inputs: invalidInputs,
expectedOutputs: invalidInputs.map(_ => false),
func: isValidName
});
}
function emailTest() {
const invalidEmails = ["@asdf.com", "what@what", "", ".."];
const validEmails = ["asdf@asdf.com", "what@what.au", "a@a.c"];
runner({
inputs: validEmails,
expectedOutputs: validEmails.map(_ => true),
func: isValidEmail
});
runner({
inputs: invalidEmails,
expectedOutputs: invalidEmails.map(_ => false),
func: isValidEmail
});
}

assert is a Node thing, which, as its name indicates, checks that the argument evaluates to true and throws an error if it’s not.

We’ve structured our tests such that there’s a runner ...