私は最近動作するアプリケーションを構築しましたが、テストを構築しようとしています。私のサービスはAPIバックエンドからアイテムを取り出す:私のコンポーネントインサイド角4:RxJSオブザーバブルでmockRespondを使用
export class CatfactService {
constructor(private http: Http) {}
getFacts() {
const url = "http://www.catfact.info/api/v1/facts.json";
return this.http.get(url).map(this.extractData)
.catch(this.handleError);
}
私はAPIレスポンスに加入することができますよ。 facts
変数の結果は、APIからの応答の詳細です:
ngOnInit() {
this.counter = this.start;
this.service.getFacts().subscribe((facts) => {
this.results = facts.facts;
});
}
は今、私はサービスのためのテストを構築しています、と妙にはメソッドは、引数を取得購読します、応答データであるという議論ではなく、最終的に嘲笑された値に解決される約束を返します。
import {
TestBed,
inject,
fakeAsync,
tick
} from '@angular/core/testing';
import {
CatfactService
} from './catfact.service';
import {
HttpModule,
Http,
BaseRequestOptions,
XHRBackend,
ResponseOptions
} from '@angular/http';
import {
MockBackend
} from '@angular/http/testing';
describe('CatfactService',() => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [
CatfactService,
MockBackend,
BaseRequestOptions,
{
provide: Http,
useFactory: (backend, options) => new Http(backend, options),
deps: [MockBackend, BaseRequestOptions]
}
],
imports: [
HttpModule
]
});
});
it('should return reasonable json', inject([CatfactService, MockBackend], fakeAsync((service: CatfactService, mockBackend) => {
const mockResponse = {
data: [{
id: 0,
details: 'All cats are lions'
},
{
id: 1,
details: 'Video 1'
},
{
id: 2,
details: 'Video 2'
},
{
id: 3,
details: 'Video 3'
},
]
};
mockBackend.connections.subscribe(connection => {
connection.mockRespond(new Response(JSON.stringify(mockResponse)));
});
service.getFacts().subscribe((facts) => {
facts.then((facts2) => {
expect(facts2.length).toBe(4);
expect(facts2[0].details).toEqual("All cats are lions");
});
});
tick();
})));
});
を購読呼び出す方法は、実際のアプリケーションでの実際の応答を返しますが、テストでの約束は、私はモックを設定していると信じて私をリードしているという事実アプリケーション内のデータが間違っています。私は角度の以下のバージョンを使用してい
は:
ng -v
_ _ ____ _ ___
/\ _ __ __ _ _ _| | __ _ _ __ /___| | |_ _|
/△ \ | '_ \/_` | | | | |/ _` | '__| | | | | | |
/___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
@angular/cli: 1.0.2
node: 7.9.0
os: darwin x64
@angular/common: 4.1.1
@angular/compiler: 4.1.1
@angular/core: 4.1.1
@angular/forms: 4.1.1
@angular/http: 4.1.1
@angular/platform-browser: 4.1.1
@angular/platform-browser-dynamic: 4.1.1
@angular/router: 4.1.1
@angular/cli: 1.0.2
@angular/compiler-cli: 4.1.1
プロジェクト全体がここにGitHubの上にある:ここでは
ありがとう、ジェイ。これはまさに問題でした。私は本当に助けに感謝します! –