Testing javascript alerts with Jasmine
18,427
Solution 1
spyOn(window, 'alert');
. . .
expect(window.alert).toHaveBeenCalledWith('a message');
Solution 2
var oldalert = alert;
alert = jasmine.createSpy();
// do something
expect(alert).toHaveBeenCalledWith('message')
alert = oldalert
Solution 3
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;}
Author by
pixelmatt
Updated on June 21, 2022Comments
-
pixelmatt about 2 years
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.
-
pixelmatt over 10 yearsThis works as well, only problem with it is that it doesn't stop the native alert function being called in Chrome, which could get annoying if you have to run lots of tests.
-
pixelmatt over 10 yearsusing the following will overwrite the native alert function for my purposes. window.alert = jasmine.createSpy().andCallFake(function (message) { console.log("fake Alert"); });`
-
Yan Foto almost 9 yearsHe/She wants to know
what the message was for the alert?
. so this solution is not really helping but to suppress the alert dialog. -
Ulterior over 7 yearsThis is a correct way to always get the last alert message
-
rook over 7 yearsHow about window.confirm with ability to confirm or dismiss?
-
vuhung3990 about 5 yearsremember
spyOn(window, 'alert');
as soon as possible, it will not work if you callexpect(window.alert)
immediately after spy -
Pedro Ferreira about 4 yearsThis IS the solution! You want the alert to get out of the testing... and all other solutions still make you click, when running the test. This one, not.
-
Pablo Jomer about 4 yearsIf you want to know the message sent in the alert use a variable and set it like this. var actualMessage; window.alert = function(message){actualMessage = message; return;}