chai
chai copied to clipboard
There is a way to intercept all custom errors messages?
Hi,
Currently I'm working on set an explicit message into the reports from protractor with chai, I know that we can set a custom message on the expects but my goal is just put the just our message and I got actually something like that: AssertionError: The create application button was not found: expected false to be true, so I need to remove 2 things for all the errors:
- AssertionError:
- expected false to be true
Is there a way to access to the message or use chai.use or anything else to remove these parts from the errors messages without overwrite all of them each one by one?
Thanks
const chai = require('chai');
function customErrorMessages(chai, utils) {
const Assertion = chai.Assertion;
// Store the original assert method
const originalAssert = Assertion.prototype.assert;
// Override the assert method
Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual, showDiff) {
// Call the original assert method
originalAssert.apply(this, arguments);
// Check if the assertion failed
if (!expr) {
// Customize the error message
const errorMessage = this.__flags.message || msg;
const customMessage = errorMessage.split(':')[0]; // Extract the custom message
const newErrorMessage = `Custom Error: ${customMessage}`;
// Create a new error with the modified message
const error = new chai.AssertionError(newErrorMessage, { actual: _actual, expected: expected, showDiff: showDiff }, utils.flag(this, 'ssfi'));
// Set the stack trace to point to the original assertion location
error.stack = new Error().stack.replace(/^Error/, 'AssertionError');
throw error;
}
};
}
// Use the custom plugin
chai.use(customErrorMessages);
// Example test case
const expect = chai.expect;
describe('Custom Error Messages', function () {
it('should customize the error message', function () {
try {
expect(false, 'The create application button was not found').to.be.true;
} catch (err) {
console.log(err.message); // Custom Error: The create application button was not found
}
});
});