在 Ember 2.16 中创建利用 window.confirm() 的集成测试?

Creating integration tests in Ember 2.16 that utilize window.confirm()?

我正在为 Ember 2.16 组件编写集成测试,我正在测试一些用户操作。

其中一个用户操作调用 window.confirm(),在删除项目之前询问用户是否确定要删除该项目。

我想测试此组件的功能,包括接受和拒绝确认。组件操作看起来类似于:

delete(id){
  if(confirm('Are you sure you want to delete?')){
    //do stuff
  } else {
    //do other stuff
  }
}

在我的集成测试中,我成功地点击了按钮以弹出提示,但我 运行 遇到了这个错误:

[Testem] Calling window.confirm() in tests is disabled, because it causes testem to fail with browser disconnect error.

如何创建绕过 window.confirm() 功能的集成测试?

我在我的组件中添加了一种绕过确认环境是否处于 "test" 模式的方法,但这并没有真正帮助,因为我没有测试依赖于 [= 的代码部分13=].

我四处查看是否有一个变量可以传递给组件以生成 window.confirm() true/false,但没有成功。

我如何创建一个测试来测试在动作中调用 window.confirm() 的组件?

我会在测试中使用像 sinon 这样的库存根 window.confirm(),我希望它被调用,以便:

  1. 希望不会出现错误信息
  2. 我知道 confirm() 实际上是由代码调用的,并且执行我的操作 希望它准确地完成(即,我可以使它成为一个简单的 fn)
  3. 可以恢复所以警告信息会记录在其他 测试(这很有帮助)

根据 testem code 它覆盖 window.confirm() 以打印此警告消息:

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

一种解决方案是保存 window.confirm 的原始实现并在测试前编写您自己的实现,然后在测试结束时恢复原始实现。

我会这样做:

// 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;
  });

});