开发者

JavaScript how to mock confirm method

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 t开发者_开发知识库o another function and then I can mock that method. However I was wondering if there is a better solution.


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.


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...


I'd think about implementing a wrapper around static methods on the window (or other) object. Then provide your wrapper to whatever uses the static method. Obviously this is easier if you are using a "class"-based implementation. Then, in order to mock the method, simply provide a different wrapper that returns the value that you want.

var windowWrapper = {
    confirm: function(msg) { return confirm(msg); },
    ...
};

var mockWrapper = {
    confirm: function(msg) { return true; },
    ...
}

var wrapper = windowWrapper;
if (test) {
    wrapper = mockWrapper;
}

...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜