我正在尝试 ember 的集成测试包 (http://emberjs.com/guides/testing/integration/),但我收到此错误
Assertion Failed: You have turned on testing mode, which disabled the run-loop's autorun.
You will need to wrap any code with asynchronous side-effects in an Ember.run
我制作了一个 JSBin 来重现此错误:http://jsbin.com/InONiLe/9,我们可以通过打开浏览器的控制台看到它。
我相信导致此错误的是load()
方法data.set('isLoaded', true);
的行App.Posts
.(链接到代码:http://jsbin.com/InONiLe/9/edit)
现在,如果我将data.set('isLoaded', true);
行包装在Ember.run()
中,那么它将按预期工作并且测试将通过。
但是,我在我的很多模型中都使用了这种模式,我不想只用Ember.run()
包装每个.set()
(转换也会触发相同的错误)。我也不想为了让测试工作而更改应用程序代码。
我还能做些什么来修复这个错误吗?
注意:我故意不在模型钩子中返回承诺,否则 UI 将被阻止,直到解决承诺。我希望立即过渡到路线,以便我可以显示加载微调器。
当你使用一些方法时,会触发异步代码,如ajax,setInterval,indexeddb api等。您需要将这些方法的解析回调委托给Ember.run
,因此 ember 会将这些操作排在您的运行循环中,并确保应用程序同步。因此,为此更改代码是处理此问题的正确方法:
App.Posts = Ember.Object.create({
load: function() {
return new Ember.RSVP.Promise(function(resolve, reject) {
var data = Ember.Object.create();
$.ajax({
url: 'https://api.github.com/users/octocat/orgs'
}).then(function() {
data.set('isLoaded', true);
Ember.run(null, resolve, data);
}, reject);
});
}
});
其他建议是始终使用 Ember.RSVP.Promise
,因为它与 Ember 的兼容性比 $.Defered
的 . $。延迟由 $.ajax
返回。
这是一个更新的 jsbin http://jsbin.com/InONiLe/10/edit
更新
因为在你的情况下,你不想返回一个承诺,所以只需删除它,只返回数据本身:
App.Posts = Ember.Object.create({
load: function() {
var data = Ember.Object.create();
$.ajax({
url: 'https://api.github.com/users/octocat/orgs'
}).then(function() {
Ember.run(function() {
data.set('isLoaded', true);
});
}, function(xhr) {
Ember.run(function() {
// if using some ember stuff put here
});
});
return data;
}
});
这是显示此工作 http://jsbin.com/InONiLe/17/edit 的 jsbin
我希望它有所帮助