Conventional asserts have a powerful alternative: power-assert. This library adds a little magic to a familiar tool.
Here's an example of a check using the standard assert module:
const user = {
name: 'Madonna',
friends: ['Kate', 'Michel'],
email: 'madonna@example.com',
};
assert(user.name === 'Michel');
// AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:
// assert(user.name === 'Michel')
The output shows the statement itself and the result of the test. But it isn't clear what the user
object is and what structure it has. To get this information, you'll have to get involved in debugging. But you can instead use the power-assert library:
import assert from 'power-assert';
// All the code remains the same
const user = {
name: 'Madonna',
friends: ['Kate', 'Michel'],
email: 'madonna@example.com',
};
// The power-assert library interface is 100% compatible with the built-in assert module
assert(user.name === 'Michel');
And look at the output:
AssertionError [ERR_ASSERTION]: # test.js:10
assert(user.name === 'Michel')
| | |
| | false
| "Madonna"
Object{name:"Madonna",friends:#Array#,email:"madonna@example.com"}
--- [string] 'Michel'
+++ [string] user.name
@@ -1,6 +1,7 @@
M
-ichel
+adonna
Try to stop and examine this conclusion carefully. What is shown here? power-assert makes debugging as easy as physically possible. It shows the value of each object and the result of each operation included in the expression passed to the assert function. In addition, at the end it compares the lines and says exactly what the difference was between them.
Here's another interesting example from the documentation:
import assert from 'power-assert';
const array = [1, 2, 3];
const zero = 0;
const two = 2;
assert(array.indexOf(zero) === two);
// AssertionError [ERR_ASSERTION]: # test.js:7
//
// assert(array.indexOf(zero) === two)
// | | | | |
// | | | | 2
// | -1 0 false
// [1,2,3]
//
// [number] two
// => 2
// [number] array.indexOf(zero)
// => -1
Impressed? Most modern frameworks don't produce an output as convenient as what power-assert does. It can be integrated with anything, but you will need additional tools to get this mapping, such as Babel / Webpack or other libraries listed in the documentation.
An example of using power-assert with Babel:
https://repl.it/@hexlet/js-testing-power-asserts-methods-en#index.test.js
The Hexlet support team or other students will answer you.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.
Programming courses for beginners and experienced developers. Start training for free
Our graduates work in companies:
Sign up or sign in
Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.