JSFiddle - React, Tailwind, and code Playground
View originalCrawl details
- Best
This article is too short to summarise.
by Fagner Brack
HTML
<div id="test-output"></div>
JavaScript
// Imagine this is public
function validateAustralianAddress(address) {
if (isEmpty({ value: address })) {
return false;
}
if (!hasSuburb(address)) {
return false;
}
// ... and other validations
return true;
}
assert('validateAustralianAddress: not valid if empty input', {
expected: false,
actual: validateAustralianAddress('')
});
assert('validateAustralianAddress: not valid if input contains only street', {
expected: false,
actual: validateAustralianAddress('Military Rd')
});
assert('validateAustralianAddress: valid if input contains a street and suburb', {
expected: true,
actual: validateAustralianAddress('Military Rd, Mosman')
});
// ... and other tests
// INTERNAL FUNCTIONS
function isEmpty(input) {
return !input.value;
};
assert('is empty: any input should be valid', {
expected: false,
actual: isEmpty({ value: 'anything' })
});
assert('is empty: empty input should be invalid', {
expected: true,
actual: isEmpty({ value: '' })
});
function hasSuburb(input) {
return input.split(',').length === 2;
}
assert('has suburb: any input after the first comma should be a valid suburb', {
expected: true,
actual: hasSuburb('Coogee Bay Rd, Coogee')
});
assert('has suburb: if there is no comma then it does not contain a valid suburb', {
expected: false,
actual: hasSuburb('Coogee Bay Rd')
});
// This can be any test library
function assert(message, { expected, actual }) {
if (expected === actual) {
document.getElementById('test-output').innerHTML += `
<span style="color: green;">
${message}: PASS!
</span>
`;
} else {
document.getElementById('test-output').innerHTML += `
<span style="color: red;">
${message}: FAIL!
</span>
`;
}
document.getElementById('test-output').innerHTML += `<hr>`
};