3

I have javascript code that raises an alert if it's being run in the browser, but which I don't want to raise alerts when I run unit tests.

I tried to solve this by having a line

if( allowAlerts === false ){
    alert = console.log;
}

but when I then run

alert("This bad thing happened");

I get back

TypeError: Illegal invocation

directly reassigning alert was a kludgey solution, and I can easily solve the problem in other ways, but I've never come across an illegal invocation error before and was hoping someone could explain what it means.

BostonJohn
  • 2,631
  • 2
  • 26
  • 48

1 Answers1

9

The console.log function needs its calling context to be the console.

Use

alert = console.log.bind(console);

Or if you want to be compatible with old IE :

alert = function(){ console.log.apply(console, arguments) };
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758