Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript how to mock confirm method

Tags:

javascript

I have following code in my JavaScript code.

if (window.confirm('Are you sure?')) {
    AdminData.actOnResult('delete');
}

I am writing test for this piece of code. How do I mock window.confirm method? I tried following code but it did not work.

window.confirm = function(arg) {
    return true;
};

I can move the window.confirm method to another function and then I can mock that method. However I was wondering if there is a better solution.

like image 977
Nick Vanderbilt Avatar asked Feb 16 '10 17:02

Nick Vanderbilt


2 Answers

Your own code works fine for me in IE. Just the following in the global scope should override it:

var confirm = function () { return true; }

EDIT
I've seen a few questions on SO in the past about trying to override confirm, mostly because they don't like it (and who would?). If you're trying to bypass it for this sort of reason, I suggest you look at changing your code to implement a callback-based replacement for confirm. Take a look at jQuery UI's modal confirm for a good example of this.

like image 131
Andy E Avatar answered Nov 08 '22 14:11

Andy E


I am using Jasmine for unit testing and have mocked alert and confirm with the following

alert = function (alertString) {debug.log('ALERT:', alertString);};

var confirmValue = true; //set this before you expect the confirm statement to be shown
confirm = function (confirmString) {
    debug.log('CONFIRM:', confirmString, confirmValue);
    return confirmValue;
};

Then I can say:

describe("test", function () {
    it('should test true confirm workflow', function () {
        confirmValue = true; // or false if you like
        //expect outcomes that would come from any confirms being called with true
    });
});

It's not perfect, and if you have multiple confirms that could pop between setting that confirmValue, you could be in trouble. Perhaps then it would be good to setup a cue of expected confirm return values... tricky...

like image 2
John David Five Avatar answered Nov 08 '22 14:11

John David Five