Search⌘ K

Unit Tests

Explore how to create simple, effective unit tests for autovalidating forms in JavaScript. Understand test structures, input-output expectations, and how to display test results on a web page without using assert, enhancing your debugging process.

We'll cover the following...

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

Javascript (babel-node)
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 ...