模拟Http后端用于Mockups

时间:2016-01-21 14:45:33

标签: angular http

有没有办法模拟Angular 2的Http对象,梦想是将它用于模型并且具有与核心代码相同的模型,除了发送到服务器的连接。

1 个答案:

答案 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})

代替组件的提供者列表。