如何测试观察Ember控制器属性的函数?
当observes方法是异步的(不立即返回)时,如何做到这一点?
控制器:
var FooController = Ember.Controller.extend({
bar: 1,
baz: null,
barObserver: function() {
var req = ic.ajax.raw({
method: 'POST',
url: '/api/bar',
data: { bar: bar },
});
return req.then(function resolve(result) {
this.set('baz', result.response.baz);
});
}.observes('bar'),
});
单元测试:
test('barObserver', function() {
var ctrl = this.subject();
equal(ctrl.get('baz'), null, 'baz initially null');
Ember.$.mockjax({
url: '/api/bar',
'type': 'POST',
dataType: 'json',
response: function() {
this.responseText = { baz: 'something' };
},
});
ctrl.set('bar', 2);
//wait for barObserver's promise (from ic.ajax.raw) to return
equal(ctrl.get('baz'), 'something', 'baz set to returned value');
});
答案 0 :(得分:1)
您也可以使用ic-ajax定义模拟的响应。此外,您可以停止并开始测试此类异步问题。
test('barObserver', function() {
var ctrl = FooController.createWithMixins(); // I was to lazy to set up ember qunit
equal(ctrl.get('baz'), null, 'baz initially null');
ic.ajax.defineFixture('/api/bar', {
response: { baz: 'something' },
jqXHR: {},
textStatus: 'success'
});
ctrl.set('bar', 2);
// allow everything else to run (skip a beat)
// and then continue testing (essentially allowing ic-ajax to resolve)
stop();
Em.run.next(function(){
start();
equal(ctrl.get('baz'), 'something', 'baz set to returned value');
});
});