有没有办法模拟Angular 2的Http对象,梦想是将它用于模型并且具有与核心代码相同的模型,除了发送到服务器的连接。
答案 0 :(得分:2)
有一个MockBackend
,确保在默认Backend
之后在DI中注册了这个,所以这个用来代替
https://angular.io/docs/ts/latest/api/http/testing/MockBackend-class.html
import {DefaultOptions, Http} from 'angular2/http';
import {MockBackend} from 'angular2/http/testing';
it('should get some data', inject([AsyncTestCompleter], (async) => {
var connection;
var injector = Injector.resolveAndCreate([
MockBackend,
provide(Http, {useFactory: (backend, defaultOptions) => {
return new Http(backend, defaultOptions)
}, deps: [MockBackend, DefaultOptions]})]);
var http = injector.get(Http);
var backend = injector.get(MockBackend);
//Assign any newly-created connection to local variable
backend.connections.subscribe(c => connection = c);
http.request('data.json').subscribe((res) => {
expect(res.text()).toBe('awesome');
async.done();
});
connection.mockRespond(new Response('awesome'));
}));
如果您想在整个应用程序中使用MockBackend
bootstrap(AppComponent, [
HTTP_PROVIDERS,
provide(XHRBackend, {useClass: MockBackend}),
provide(JSONPBackend, {useClass: MockBackend})]);
确保MockBackend
提供商在HTTP_PROVIDERS
之后。
如果您希望MockBackend
仅由特定组件使用,请添加
provide(XHRBackend, {useClass: MockBackend}),
provide(JSONPBackend, {useClass: MockBackend})
代替组件的提供者列表。