JS: Automated testing
Theory: Assertions
Each test we wrote for capitalize() is commonly referred to as an assert. Asserts are a vital part of testing. They're the assertions about the code functionality:
You may have noticed that all checks have the same structure: condition => exception. Node.js comes with an assert module that has several functions to make it easier to write asserts:
At its simplest, assert is used as a function that checks the truth of a value passed to a function. In other words, assert(true) means all is well, and assert(false) indicates an error. The last option throws an exception with this message:
AssertionError [ERR_ASSERTION]: false == true
It basically means, "the value of the expression was expected to be true, but it turned out to be false". In addition to the message, it also displays a backtrace to specify the statement that triggered the message:
The assert() made our code shorter and easier to understand. A positive check looks more natural because it's what we expect.
On the other hand, the error message is extremely uninformative. The only way to figure out what happened is to open the code with the dodgy statement (there's also an option to pass the error message with the last parameter, but this is rarely done because it requires too much effort). You can enhance this using specialized statements designed for particular cases. For example, when comparing two values, the assert.strictEqual(actual, expected) function is a good choice. Let's rewrite the code above:
The output from these assertions is much clearer now:
Thrown:
AssertionError [ERR_ASSERTION]: 'hello' == 'Hello'
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 'hello',
expected: 'Hello',
operator: '=='
This output contains not only information about the error, but also the data that was passed to the assertion. This format simplifies problem analysis and speeds up debugging.
However, you should be careful. The strictEqual(actual, expected) function performs equality check by reference. I.e., two different objects with the same content will not be treated as though they are equivalent:
There's a different assertion we use to compare values: assert.deepEqual(actual, expected). It relies only on the content:
Actually, the rules for checking using function are quite complicated. You can read more about it in the documentation
The functions assert.notStrictEqual(actual, expected) and assert.notDeepStrictEqual(actual, expected) are designed to test negative scenarios. They test to see if the values are NOT equal, not to see if they ARE equal. These assertions are rarely used, but it's still useful to know about them:

