【问题标题】:Creating integration tests in Ember 2.16 that utilize window.confirm()?在 Ember 2.16 中创建使用 window.confirm() 的集成测试?
【发布时间】:2019-10-17 21:45:21
【问题描述】:

我正在为 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() 功能的集成测试?

我已经在我的组件中添加了一种方法来绕过确认环境是否处于“测试”模式,但这并没有真正帮助,因为我没有测试依赖于 window.confirm() 的代码部分。

我环顾四周,看看是否有一个变量可以传递给组件以使window.confirm() 为真/假,但没有成功。

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

【问题讨论】:

    标签: javascript ember.js integration-testing


    【解决方案1】:

    一种解决方案是保存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;
      });
    
    });
    

    【讨论】:

    • 这太棒了!我在想我可以“模拟”它,但没有意识到它就像在我的集成测试中用函数调用替换它一样简单。非常感谢。
    【解决方案2】:

    我会在测试中使用像 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-23
      • 1970-01-01
      相关资源
      最近更新 更多