[英]angular2 testing framework async testing issue
我已經創建了角度2項目和帶有angular-cli的服務,並試圖測試我的服務。
但是API在async函數中不會失敗,盡管它應該失敗;而且,它只是忽略了那些異常。
/* tslint:disable:no-unused-variable */
import {
beforeEach, beforeEachProviders, describe, xdescribe,
expect, it, xit, async, inject, injectAsync
} from '@angular/core/testing';
import { SearchService } from './search.service';
import {provide} from '@angular/core';
import {MockBackend, MockConnection} from '@angular/http/testing';
import {XHRBackend, Response, ResponseOptions, HTTP_PROVIDERS} from '@angular/http';
describe('Search Service', () => {
let searchService: SearchService;
let mockBackend: MockBackend;
beforeEachProviders(() => [
HTTP_PROVIDERS,
MockBackend,
provide(XHRBackend, { useClass: MockBackend }),
SearchService
]);
beforeEach(injectAsync([SearchService, MockBackend], (s, m) => {
searchService = s;
mockBackend = m;
}));
it('async test', () => {
setTimeout(() => {
expect(2).toBe(1);
}, 3000);
});
它只是忽略了那些最小的測試用例。
然后我讀了一些文檔並更新了我的代碼如下。
it('async test with done', (done) => {
setTimeout(() => {
expect(1).toBe(1);
done();
}, 1000);
});
但是這一次,測試失敗了,盡管它應該通過。 錯誤如下。
錯誤:超時 - 在jasmine.DEFAULT_TIMEOUT_INTERVAL指定的超時內未調用異步回調。
我將默認超時值更改為更大的值但它沒有效果。
injectAsync
不起作用,使用async
(在rc2之后停止為我工作)
injectAsync現已棄用。 相反,使用async函數來包裝任何異步測試。 您還需要在Karma或其他測試配置中將依賴項“node_modules / zone.js / dist / async-test.js”添加為服務文件。
之前:
it('should wait for returned promises', injectAsync([FancyService], (service) => {
return service.getAsyncValue().then((value) => { expect(value).toEqual('async value'); });
}));
it('should wait for returned promises', injectAsync([], () => {
return somePromise.then(() => { expect(true).toEqual(true); });
}));
后:
it('should wait for returned promises', async(inject([FancyService], (service) => {
service.getAsyncValue().then((value) => { expect(value).toEqual('async value'); });
})));
// Note that if there is no injection, we no longer need `inject` OR `injectAsync`.
it('should wait for returned promises', async(() => {
somePromise.then(() => { expect(true).toEqual(true); });
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.