Show expected and actual values for assertion failures

Viewed 2416

When writing assertions for my tests, the assertion failures don't provide enough information without needing to open an IDE and start debugging.

For example, I have some code that uses the 'assert' library:

import * as assert from 'assert'

// some code

assert(someObject.getValue() === 0)

I just get

       AssertionError [ERR_ASSERTION]: false == true
           + expected - actual

           -false
           +true

This error message isn't really meaningful. As a workaround, I added it in the message in the assertion:

assert(someObject.getValue() === 0, 
       '\nActual: ' + someObject.getValue() + 
       '\nExpected: ' + 0)

Is there a better, cleaner way to just show the expected & actual values without overriding the message on every assertion? I also tried to create an assert wrapper, but I wasn't able to extract the actual and expected values from the expression.

EDIT: assert.strictEqual resolves this issue for equalities only. But as soon as any other operator is included, then we have the same issue (e.g. assert(someObject.getValue() > 0)

Any advice would be appreciated.

Thanks!

1 Answers

You can use assert.strictEqual(actual, expected[, message]) to get actual/expected error messages without the need of the third message argument:

assert.strictEqual(someObject.getValue(), 0)

You'd get an error message such as:

// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
//
// 1 !== 0

Hopefully that helps!

Related