繁体   English   中英

使用Jasmine监视console.error()

[英]Spying on console.error() with Jasmine

我实际上是JavaScript和Jasmine的新手。 所以它可能是非常明显的解决我的问题,但我看不到它。

我想检查(一个已经存在的)JavaScript应用程序在加载时是否调用console.error() 我真的没有看到如何用Jasmine实现这一点。 我已经在SpecRunner.html包含了JavaScript文件以及spec文件。 但我认为我以某种方式需要“实例化”应用程序以测试它是否会在控制台上抛出任何错误,对吧?

或者我应该仅为此目的将SpecRunner.html代码包含在应用程序的HTML代码中?

你可以像这样窥探console.error

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

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

您可以像这样覆盖标准的console.error函数:

//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' );

此解决方案适用于Jasmin或其他任何方式。 只需将代码放在其他代码之前,然后调用console.error()之后的任何调用将调用重写的函数。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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