Set Custom Error Message for Assert (Node.js)


Set Custom Error Message for Assert (Node.js)



I'm lost in the Node documentation and I'm having difficulties figuring out how I could create a custom (or modify the existing) error handling for all of my assert statements, without having to include individual messages with each assertion.


const assert = require('assert');

describe('Test 1', function(){
describe('Checks State', function(){
it('will fail', function(){
assert.strictEqual(true, false);
});
});
});



As expected, the previous code would just generate something like:


1) "Test 1 Checks State will fail"
true === false



I'm running with WebDriverIO and my goal is to include the browser.sessionId in the error message, without having to manually fill in the third (message) parameter on each test.


browser.sessionId


assert.strictEqual(true, false, browser.sessionId);



It would be ideal if I could generate an error message like:


1) "Test 1 Checks State will fail"
abc012-efg345-hij678-klm901
true !== false



I apologize, I know I should include "what I have done so far" -- but everything I've done so far has had no impact. And again, I'm lost in the node documentation :)




1 Answer
1



You cannot, without tampering with the 3rd party lib assert


assert



Behind the scenes, uses a fail function, that is private in the context of assert and you cannot tell assert to use a custom fail function.


fail


assert


assert


fail



this is the function used behind the scenes:


function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}



As such, you have three options:



(recommended) Fork the lib on github. Implement either some watchers like onFail or allow it to be extensible and create a pull request.


onFail



(not recommended) Overwrite the fail function in the node_modulesassertassert.js file yourself so that, besides triggering the usual stuff, it does what you want as well.


fail


node_modulesassertassert.js



While quick, this will cause a broken dependency forever.



Look for other assertions libraries (if there are any that fit your needs)





Thanks -- even though the answer is that I can't achieve what I'm looking for with assert, it's good to know that I haven't just been missing something obvious and I can now move on with your recommended next steps :)
– Doug
Jul 2 at 14:24






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages