使用 Jasmine 测试 JavaScript 警报
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19519328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Testing javascript alerts with Jasmine
提问by pixelmatt
I'm writing some Jasmine tests for some legacy javascript that produces an alert or a confirm at some points in the code.
我正在为一些遗留 javascript 编写一些 Jasmine 测试,这些测试在代码的某些点产生警报或确认。
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.
谢谢你的帮助。
回答by jolySoft
spyOn(window, 'alert');
. . .
expect(window.alert).toHaveBeenCalledWith('a message');
回答by Yaroslav
var oldalert = alert;
alert = jasmine.createSpy();
// do something
expect(alert).toHaveBeenCalledWith('message')
alert = oldalert
回答by Pablo Jomer
Another way is to do this in spec helper.
另一种方法是在规范助手中执行此操作。
window.alert = function(){return;};
回答by Vidya
You simply create a spy, surprisingly with createSpy()
, to mock the function that contains the alert. So you can do something like this:
您只需创建一个间谍,令人惊讶的是使用createSpy()
,来模拟包含警报的函数。所以你可以做这样的事情:
beforeEach(function() {
functionWithAlert = jasmine.createSpy("functionWithAlert");
functionWithAlert("called as usual");
});
You can also do this to return something
你也可以这样做来返回一些东西
oldFunctionWithAlert = jasmine.createSpy("oldFunctionWithAlert() spy").andCallFake(function() {
console.log("Doing some testing");
return "Test";
});
On a side note, I would suggest you replace the alert if possible with less disruptive alternatives. There are a ton of options out there like JQuery UI dialog.
附带说明一下,如果可能,我建议您用破坏性较小的替代方案替换警报。有很多选项,比如JQuery UI 对话框。