[英]How to do a unit test for Http get MockBackend in Angular2?
[英]How to properly unit test an Angular2 http service with the MockBackend?
運行npm test
此錯誤:
src/client/app/shared/services/scientist.service.spec.ts(20,7): error TS2345: Argument of type 'Function' is not assignable to parameter of type '(done: () => void) => void'.
Type 'Function' provides no match for the signature '(done: () => void): void'
我正在使用這個 angular2 種子: https : //github.com/mgechev/angular2-seed ,我更改了科學家姓名列表服務以從 http 獲取數據,基於此博客: http : //chariotsolutions.com/博客/帖子/testing-http-services-angular-2-jasmine/ 。
因此,我使用從 json 創建實例的asScientist
和asScientists
方法創建了Scientist
類。
科學家.service.ts:
import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import {Scientist} from './scientist';
@Injectable()
export class ScientistService {
private url = 'http://path/to/scientists/';
constructor(private http:Http) {
}
get():Observable<Scientist[]> {
return this.http.get(this.url)
.map((res:Response) => {
return Scientist.asScientists(res.json());
});
}
}
科學家.service.spec.ts:
import {provide} from 'angular2/core';
import {beforeEachProviders, inject} from 'angular2/testing';
import {XHRBackend, ResponseOptions, Response} from 'angular2/http';
import {MockBackend, MockConnection} from 'angular2/src/http/backends/mock_backend';
import {Scientist} from './scientist';
import {ScientistService} from './scientist.service.ts';
export function main() {
describe('Scientist Service', () => {
beforeEachProviders(() => {
return [HTTP_PROVIDERS, provide(XHRBackend, {useClass: MockBackend}), ScientistService];
});
it('should get the list of scientists',
// ##### Line below causes the error #####
inject([XHRBackend, ScientistService], (mockBackend:MockBackend, scientistService:ScientistService) => {
mockBackend.connections.subscribe(
(connection:MockConnection) => {
// Haven't changed these yet since I want to make the test pass first
connection.mockRespond(new Response(
new ResponseOptions({
body: [
{
id: 26,
contentRendered: '<p><b>Hi there</b></p>',
contentMarkdown: '*Hi there*'
}]
}
)));
});
scientistService.get().subscribe((scientists:Scientist[]) => {
expect(scientists.length).toBe(1);
//expect(scientists[0].id).toBe(26);
//expect(data[0].contentMarkdown).toBe('*Hi there*');
},
(error:any) => {
// we can call a failure case here...
fail(error);
});
}));
});
}
這似乎是一個語法錯誤,但不是一個很明顯的錯誤,所以任何形式的幫助都將不勝感激!
也許您需要從 angular2/testing 模塊導入所有測試方法。
像這樣:
import {it, beforeEachProviders, describe, expect, beforeEach, inject, injectAsync} from 'angular2/testing';
因為在您的代碼中,我看到您只導入了“beforeEachProviders”和“inject”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.