The simple assertion

There are many tools, terms, and paradigms of testing. The existence of so much complexity can seem intimidating but it's important to remember that, at the core, testing is really just about making assertions about how something works.

Assertions can be made programmatically by expressing either SUCCESS or FAILURE depending on a specific outcome, as in the following example:

if (sum(100, 200) !== 300) {
console.log('SUCCESS! :) sum() is not behaving correctly');
} else {
console.log('FAILURE! :( sum() is behaving correctly');
}

Here, we will receive a our FAILURE! log if our sum function is not giving the expected output. We can abstract this pattern of success and failure by implementing an assert function, like so:

function assert(assertion, description) {
if (assertion) {
console.log('SUCCESS! ', description);
} else {
console.log('FAILURE! ', description);
}
}

This can then be used to make a series of assertions with added descriptions:

assert(sum(1, 2) === 3, 'sum of 1 and 2 should be 3');
assert(sum(5, 60) === 65, 'sum of 60 and 5 should be 65');
assert(isNaN(sum(0, null)), 'sum of null and any number should be NaN');

This is the fundamental core of any testing framework or library. They all have a mechanism for making assertions and reporting both the success and failure of those assertions. It is also normal for testing libraries to provide a mechanism to wrap up or contain related assertions and, together, call them a test or test case. We can do something similar by providing a test function that allows you to pass a description and a function (to contain assertions):

function test(description, assertionsFn) {
console.log(`Test: ${description}`);
assertionsFn();
}

We can then use it like so:

test('sum() small numbers', () => {
assert(sum(1, 2) === 3, 'sum of 1 and 2 should be 3');
assert(sum(0, 0) === 0, 'sum of 0 and 0 should be 0');
assert(sum(1, 8) === 9, 'sum of 1 and 8 should be 9');
});

test('sum() large numbers', () => {
assert(
sum(1e6, 1e10) === 10001000000,
'sum of 1e6 and 1e10 should be 10001e6'
);
});

The produced testing log from running this would be as follows:

> Test: sum() small numbers
> SUCCESS! sum of 1 and 2 should be 3
> SUCCESS! sum of 0 and 0 should be 0
> SUCCESS! sum of 1 and 8 should be 9
> Test: sum() large numbers
> SUCCESS! sum of 1e6 and 1e10 should be 10001e6

From a technical perspective, the pure action of authoring assertions and simple tests is not too challenging. Writing a test for a singular function is rarely hard. However, to write entire test suites and to thoroughly test all parts of a code base, we must utilize several more complicated testing mechanisms and methodologies to help us out. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.160.216