We do use console.assert in our code base as part of defensive programming in order to check some complicated code parts and annotate assumptions about what is being done in the code/the values it calculates/assumes etc.
Example:
function calculateSomething(a, b, c) {
// assume, we know that the calculation result below should never be negative, because other logic assures that (b - c) < a (This is just an example.)
// or that check is implemented here, but just to make sure you put that negative check before returning the value
const result = a - (b - c);
console.assert(result > 0, 'result must not be negative, but was', result);
return result;
}
console.log('result 1:', calculateSomething(1, 2, 3)); // fails
console.log('result 2:', calculateSomething(1, 3, 2)); // works
Now, we noticed that this only fails/prints an error message in the console in production code/usual code runs, but explicitly not when the tests execute the code.
How can you make console.assert also fail in tests?
Okay, I guess you can just stub it and, as it may be useful, keep the original callThrough in addition to callFake. Just put this into your beforeEach and your tests will honor console.assert and treat it as a failure:
Typescript version:
const realConsoleAssert = console.assert;
assertSpy = spyOn(console, 'assert').and.callFake((assertion: any, message?: string, ...optionalParams: any[]) => {
realConsoleAssert(assertion, message, ...optionalParams);
expect(assertion).toBeTruthy(`${message} ${optionalParams.concat(' ')}`);
});
JavaScript version:
const realConsoleAssert = console.assert;
assertSpy = spyOn(console, 'assert').and.callFake((assertion, message, ...optionalParams) => {
realConsoleAssert(assertion, message, ...optionalParams);
expect(assertion).toBeTruthy(`${message} ${optionalParams.concat(' ')}`);
});
Especially the optionalParams is not ideal yet and does not treat it as elegantly as console.assert can, e.g. undefined is converted into an empty string while the browser version will print it properly, but that's just a minor detail IMHO.