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;}
Share:
18,427
pixelmatt
Author by

pixelmatt

Updated on June 21, 2022

Comments

  • pixelmatt
    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
    pixelmatt over 10 years
    This 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
    pixelmatt over 10 years
    using the following will overwrite the native alert function for my purposes. window.alert = jasmine.createSpy().andCallFake(function (message) { console.log("fake Alert"); });`
  • Yan Foto
    Yan Foto almost 9 years
    He/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
    Ulterior over 7 years
    This is a correct way to always get the last alert message
  • rook
    rook over 7 years
    How about window.confirm with ability to confirm or dismiss?
  • vuhung3990
    vuhung3990 about 5 years
    remember spyOn(window, 'alert'); as soon as possible, it will not work if you call expect(window.alert) immediately after spy
  • Pedro Ferreira
    Pedro Ferreira about 4 years
    This 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
    Pablo Jomer about 4 years
    If 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;}