简体   繁体   中英

Spying on console.error() with Jasmine

I'm actually new to JavaScript as well as Jasmine. So it might be something really obvious that fixes my problem but I can't see it.

I want to check if (an already existing) JavaScript application calls console.error() while loading. I don't really see a way how to realise this with Jasmine. I've included the JavaScript file as well as the spec file in the SpecRunner.html . But I take it that I somehow need to "instantiate" the application in order to test if it throws any errors on the console, right?

Or should I include the SpecRunner.html code only for this purpose into the HTML code of the app?

You can spy on console.error like this:

beforeEach(function(){
  spyOn(console, 'error');
})

it('should print error to console', function(){
  yourApp.start();
  expect(console.error).toHaveBeenCalled();
})

You can override the standard console.error function like this:

//call the error function before it is overriden
console.error( 'foo' );

//override the error function (the immediate call function pattern is used for data hiding)
console.error = (function () {
  //save a reference to the original error function.
  var originalConsole = console.error;
  //this is the function that will be used instead of the error function
  function myError () {
    alert( 'Error is called. ' );
    //the arguments array contains the arguments that was used when console.error() was called
    originalConsole.apply( this, arguments );
  }
  //return the function which will be assigned to console.error
  return myError;
})();

//now the alert will be shown in addition to the normal functionality of the error function
console.error( 'bar' );

This solution works with Jasmin or anything else. Just put the code above before the other codes and any call after this to console.error() will call the overridden function.

使用toThow和toThrowError http://jasmine.github.io/edge/introduction#section-Spies:_and.throwError

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM