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

故事扮演 提交于 2019-12-11 12:08:56

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/29432512/how-can-i-unit-test-a-method-that-results-in-an-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!