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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With