Javascript 在Ember 2.16中创建利用window.confirm()的集成测试?
我正在为Ember 2.16组件编写集成测试,并且正在测试一些用户操作 其中一个用户操作调用了Javascript 在Ember 2.16中创建利用window.confirm()的集成测试?,javascript,ember.js,integration-testing,Javascript,Ember.js,Integration Testing,我正在为Ember 2.16组件编写集成测试,并且正在测试一些用户操作 其中一个用户操作调用了window.confirm(),其中会询问用户是否确定要在删除某个项目之前删除该项目 我想测试这个组件的功能,包括接受和拒绝确认。组件操作与此类似: delete(id){ if(confirm('Are you sure you want to delete?')){ //do stuff } else { //do other stuff } } 在我的集成测试中,我
window.confirm()
,其中会询问用户是否确定要在删除某个项目之前删除该项目
我想测试这个组件的功能,包括接受和拒绝确认。组件操作与此类似:
delete(id){
if(confirm('Are you sure you want to delete?')){
//do stuff
} else {
//do other stuff
}
}
在我的集成测试中,我成功地单击按钮以显示提示,但我遇到了以下错误:
[Testem]在测试中调用window.confirm()被禁用,因为它会导致Testem失败,出现浏览器断开连接错误。
如何创建一个绕过窗口.confirm()功能的集成测试
我在组件中添加了一种绕过确认环境是否处于“测试”模式的方法,但这并没有真正起到帮助作用,因为我没有测试依赖于窗口的代码部分。confirm()
我环顾四周,看看是否有一个变量可以传递给组件,以生成窗口。confirm()
true/false,但没有成功
如何创建一个测试来测试在操作中调用window.confirm()
的组件?我将在测试中使用一个库来存根window.confirm()
,就像我希望调用它的地方一样,以便:
希望该错误消息不会出现
我知道confirm()
实际上是由代码调用的,并执行我所做的操作
希望它准确地执行(即,我可以使它成为一个简单的fn)
可以将其还原,以便将警告消息记录在其他日志中
测试(这很有帮助)
根据提示,它将覆盖窗口。确认()
以打印此警告消息:
window.confirm = function() {
throw new Error('[Testem] Calling window.confirm() in tests is disabled, because it causes testem to fail with browser disconnect error.');
};
因此,在与sinon的测试中这样做应该是可行的:
const confirm = sinon.stub(window, "confirm").callsFake(() => {
// fake implementation here which overwrites the testem implementation
});
// rest of the test
confirm.restore(); // restores the testem implementation
一种解决方案是保存窗口的原始实现。在测试之前确认并编写自己的实现,然后在测试结束时恢复原始实现
我会这样做:
// Watch out, this test is written with the latest ember-qunit syntax which might not be exactly what you have in your Ember 2.16 application
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from 'ember-test-helpers';
import hbs from 'htmlbars-inline-precompile';
module('your component integration tests', function(hooks) {
setupRenderingTest(hooks);
test('clicking the OK confirm button', async function(assert) {
// save the original window.confirm implementation
const originalWindowConfirm = window.confirm;
// simulate the OK button clicked
window.confirm = function() { return true;}
// ADD YOUR TEST AND ASSERTIONS HERE
// restore the original window.confirm implementation
window.confirm = originalWindowConfirm;
});
});
这太棒了!我想我可以“模仿”它,但没有意识到这就像在集成测试中用函数调用替换它一样简单。非常感谢你。