問題描述
我正在使用一個函數從 webapi 獲取數據.基本使用$.ajax
.
I'm using a function to fetch data from webapi. Basicly using $.ajax
.
我現在用 waits()
測試它,如下所示:
I'm now testing it with waits()
like this:
describe('xxxxxxxxxxxxxxxxxxxxx', function () {
var r;
it('fetchFilter', function () {
runs(function () {
model.fetch(opts)
.done(function(data) {
r = data;
});
});
waits(2000);
runs(function () {
expect(r[0].gender).toBeDefined();
});
});
});
問題是:
- 不保證
waits(2000)
能很好地完成這項工作.由于各種原因(網絡連接、api本身的算法效率等),我可能不得不waits(5000)
或更多,或者對于某些模型waits(500)
就足夠了.而最煩人的是,一切都失控了. - 大量的
waits()
使得 test-specs-runs 浪費了大量的時間等待.運行整個套件的時間太長,無法接受.
- It's not guaranteed that
waits(2000)
will do the job well. Due to various reasons(network connections, algorithm efficiency of the api it self, etc.), I may have towaits(5000)
or more, or for some modelswaits(500)
is enough. And the most annoying thing is that it's all out of control. - A lot of
waits()
makes the test-specs-runs waste a lot of time waiting. The time of running the whole suite is too long to accept.
是否有一些最佳實踐
可以做這些事情?
Is there some best practice
of doing there kind of things?
PS:我知道單元測試不應該應用于某些依賴 webapi 或數據庫的功能.但我正在使用單頁 js-heavy-webapp.數據獲取過程與我將如何在 js 模型中使用它們一樣重要.
PS: I know that unit test should not be applied to some function that relies on webapi or database. But I'm working with a single-page-js-heavy-webapp. The data fetching process is as important as how I will consume them with js models.
推薦答案
waitsFor()
會等待指定的latch回調返回true
(會嘗試很多次每隔幾毫秒).如果超過指定的超時時間(本例中為 5000 毫秒),它也會引發異常.
waitsFor()
will wait for a specified latch callback to return true
(it will try many time every few ms). It will also raise an exception if the specified timeout (5000ms in this case) is exceeded.
describe('xxxxxxxxxxxxxxxxxxxxx', function () {
var r, fetchDone;
it('fetchFilter', function () {
runs(function () {
model.fetch(opts).done(function(data) {
r = data;
fetchDone = true;
});
});
waitsFor(function() {
return fetchDone;
}, 5000);
runs(function () {
expect(r[0].gender).toBeDefined();
});
});
});
查看 Jasmine 文檔 了解有關 waitsFor()
的更多信息和runs()
Check the Jasmine docs for more info on waitsFor()
and runs()
這篇關于如何使用 jasmine 測試一個需要很長時間才能響應的異步函數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!