我有一个执行异步操作的控制器,我想测试它:
/*globals Ember, momnent*/
import { raw as icAjaxRaw } from 'ic-ajax';
//...
actions: {
foo: function() {
var req = icAjaxRaw({
type: 'POST',
url: ApiUtils.apiUrl+'/dofoo',
processData: false,
});
return req.then(
function resolve(result) {
console.log(result.response);
this.set('fooLastDoneAt', moment());
}.bind(this)
);
},..。在测试中:
test('actions.foo', function() {
expect(2);
var ctrl = this.subject();
var model = {
fooLastDoneAt: moment().add(-10, 'days'),
};
ctrl.set('model', model);
ok(ctrl.get('fooLastDoneAt').isBefore(moment().add(-1, 'days')), true, 'initial');
ctrl.send('foo');
ok(ctrl.get('fooLastDoneAt').isBefore(moment().add(-1, 'days')), false, 'updated date');
});然而,这不可避免地导致在另一个无关的测试用例中抛出错误:
"Uncaught Error: Assertion Failed: calling set on destroyed object"[这必须发生,因为this.set('fooLastDoneAt', moment());是在测试用例完成后执行的,并且测试运行程序已经为该模块执行了一个teardown,并继续执行下一个模块;而该操作仍在执行中。
在进入下一步单元测试之前,是否有一种方法可以让我等待动作异步完成?
@kingpin2k建议使用这个解决方案,将承诺延迟的对象传递到操作中。然而,在我的应用程序中,应用程序本身永远不会这样做,如果我只需要修改我的应用程序源代码就可以测试它,这似乎是一个根本的问题--特别是因为它增加了复杂性。
是否有其他方法让测试执行等待操作完成?
发布于 2014-07-16 09:20:15
我会选择QUnit start() stop()函数。
下面是从QUnit文档中获取的示例:
QUnit.test( "a test", function( assert ) {
QUnit.stop();
asyncOp();
setTimeout(function() {
assert.equals( asyncOp.result, "someExpectedValue" );
QUnit.start();
}, 150 );
});另外,余烬-q单位库用then来介绍这一点。
下面是ember-qunit的示例
test('actions.foo', function() {
expect(2);
var ctrl = this.subject();
var model = {
fooLastDoneAt: moment().add(-10, 'days'),
};
ctrl.set('model', model);
ok(ctrl.get('fooLastDoneAt').isBefore(moment().add(-1, 'days')), true, 'initial');
ctrl.send('foo').then(function(){
ok(ctrl.get('fooLastDoneAt').isBefore(moment().add(-1, 'days')), false, 'updated date');
});
});我没有测试代码,所以我希望它能解决你的问题
https://stackoverflow.com/questions/24772377
复制相似问题