Search code examples
javascriptember.jsintegration-testing

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


I am writing integration tests for an Ember 2.16 component and I am testing some user actions.

One of the user actions calls window.confirm(), where the user is asked if they are sure they want to delete an item before the item is deleted.

I want to test the functionality of this component, both with accepting and declining the confirm. The component action looks similar to this:

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

Inside my integration tests I am successfully clicking the button to bring up the prompt, but I am running into this error:

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

How can I create an integration test that will bypass the window.confirm() functionality?

I have added in my component a way to bypass the confirm if the env is in "test" mode, but this does not really help as I am not testing the portion of code that relies on the window.confirm().

I have looked around to see if there is a variable I can pass to the component to make the window.confirm() true/false, but have been unsuccessful.

How can I create a test that will test a component that calls window.confirm() inside an action?


Solution

  • One solution would be to save the original implementation of window.confirm and write your own implementation before your test, then restore the original implementation at the end of the test.

    This is how I would do it:

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