我如何单元测试导致Action的方法 [英] How can I unit test a method that results in an Action
本文介绍了我如何单元测试导致Action的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
...
let searchText = this.get('searchText')&&
this.get('searchText')。trim()。toLowerCase();
this.sendAction('searchTextChanged',searchText);
...
我如何单元测试此功能在qunit测试?我无法弄清楚如何听取动作结果。我正在使用 ember-cli - qunit,助手等附带的测试功能。
解决方案
Ember有一个关于如何做的指南 here 。我将把代码放在这里,以便指南改变。
给定这个组件:
App.MyFooComponent = Ember.Component.extend({
layout:Ember.Handlebars.compile(< button {{action'doSomething'}}>< / button>) ,
actions:{
doSomething:function(){
this.sendAction('internalAction');
}
}
} );
您可以测试这样的操作:
moduleForComponent('my-foo','MyFooComponent');
测试('按钮被点击时触发外部操作',function(){
//告诉我们的测试期望1个断言
expect(1);
//组件实例
var component = this.subject();
//组件dom实例
var $ component = this.append();
var targetObject = {
externalAction:function(){
//我们有这个断言是
//当触发动作时调用
OK(true,'external Action was called!');
}
};
//设置一个假的外部动作,当
//按钮点击
component.set('internalAction','externalAction');
//将targetObject设置为我们的虚拟对象(这个
//是sendAction将发送它的位置action to)
component.set('targetObject',targetObject);
//单击按钮
click('button');
});
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.
解决方案
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');
});
这篇关于我如何单元测试导致Action的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文