Search code examples
ember.jsember-cliqunit

How can I unit test a method that results in an Action


In my Ember application, I have a simple form component, with the following behavior (snippet):

...
let searchText = this.get('searchText') &&
  this.get('searchText').trim().toLowerCase();

this.sendAction('searchTextChanged', searchText);
...

How can I unit test this functionality in a qunit test? I'm unable to figure out how to listen for the action result. I'm using the test functionality that comes with ember-cli -- qunit, the helpers, etc.


Solution

  • Ember has a guide on how to do that here. I'll put the code here in case the guide changes.

    Given this component:

    App.MyFooComponent = Ember.Component.extend({
      layout:Ember.Handlebars.compile("<button {{action 'doSomething'}}></button>"),
    
      actions: {
        doSomething: function() {
          this.sendAction('internalAction');
        }
      }
    });
    

    You would test the action like this:

    moduleForComponent('my-foo', 'MyFooComponent');
    
    test('trigger external action when button is clicked', function() {
      // tell our test to expect 1 assertion
      expect(1);
    
      // component instance
      var component = this.subject();
    
      // component dom instance
      var $component = this.append();
    
      var targetObject = {
        externalAction: function() {
          // we have the assertion here which will be
          // called when the action is triggered
          ok(true, 'external Action was called!');
        }
      }; 
    
      // setup a fake external action to be called when 
      // button is clicked
      component.set('internalAction', 'externalAction');
    
      // set the targetObject to our dummy object (this
      // is where sendAction will send its action to)
      component.set('targetObject', targetObject);
    
      // click the button
      click('button');
    });