How to make Karma / Jasmine tests fail on console errors

I had a good google for this problem, and couldn’t find a solution, so I though I’d put my own here.

I’m running Jasmine tests through Karma. One of the components I’m testing logs error messages to the console, which is the desired behaviour in production but makes testing hard because methods fail silently.

This code snippet causes any calls to console.error(message) to throw an exception, ensuring that any tests that trigger errors will fail.

The code sample uses Jasmine, but the same technique will work in any testing framework:

describe('TestSuite', function() {
  var oldError = console.error;
  beforeEach(function() {
    console.error = function(message) {
      throw new Error(message);
    };
  });
  return afterEach(function() {
    return console.error = oldError;
  });
 
  it('should fail', function() {
    console.error("Oops!")
  });