Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing javascript alerts with Jasmine

I'm writing some Jasmine tests for some legacy javascript that produces an alert or a confirm at some points in the code.

At the moment where the alert pops up it pauses execution in the browser requiring me to press ok before going on.

I'm sure I'm missing something but is there a way of faking an alert?

Even better is it possible to find out what the message was for the alert?

Thanks for your help.

like image 961
pixelmatt Avatar asked Oct 22 '13 13:10

pixelmatt


People also ask

How do I get alerts in JavaScript?

The alert() method in JavaScript is used to display a virtual alert box. It is mostly used to give a warning message to the users. It displays an alert dialog box that consists of some specified message (which is optional) and an OK button. When the dialog box pops up, we have to click "OK" to proceed.

What is JavaScript alert ()?

The alert() method displays an alert box with a message and an OK button. The alert() method is used when you want information to come through to the user.


3 Answers

spyOn(window, 'alert');
. . . 
expect(window.alert).toHaveBeenCalledWith('a message');
like image 55
jolySoft Avatar answered Oct 16 '22 12:10

jolySoft


var oldalert = alert;
alert = jasmine.createSpy();
// do something
expect(alert).toHaveBeenCalledWith('message')
alert = oldalert
like image 4
Yaroslav Avatar answered Oct 16 '22 12:10

Yaroslav


Another way is to do this in spec helper.

window.alert = function(){return;};

Or if you need the message.

var actualMessage = ''; 
window.alert = function(message){actualMessage = message; return;}
like image 2
Pablo Jomer Avatar answered Oct 16 '22 10:10

Pablo Jomer