将Angular2响应用于本地开发

时间:2016-05-02 23:57:40

标签: angular

在angular1中,当我在本地开发时,我能够使用$ httpBackend来存根/模拟http调用。它会有点像这样:

$httpBackend
  .whenGET('/api/v1/accounts/ticker')
  .respond({data: [1,2,3]})

如何在Angular2中为本地开发做类似的事情?

1 个答案:

答案 0 :(得分:0)

<强>更新

describe('...', () => {

  beforeEach(() => {

    TestBed.configureTestingModule({
      declarations: [TestComponent],
      providers: [
        MockBackend
        {provide: XHRBackend, useExisting: MockBackend},
        {provide: JSONPBackend, useExisting: MockBackend}
      ],
      imports: [HttpModule]
    });
  });

  it('...', () => {
    const fixture = TestBed.createComponent(TestComponent);
  });
});

<强>原始

bootstrap(AppComponent, [
    HTTP_PROVIDERS, 
    provide(XHRBackend, {useClass: MockBackend}),
    provide(JSONPBackend, {useClass: MockBackend})]);

然后注入MockBackend并像

一样使用它
backend.connections.subscribe(c => connection = c);
  http.request('data.json').subscribe((res) => {
    expect(res.text()).toBe('awesome');
    async.done();
  });
  connection.mockRespond(new Response('awesome'));

您可以将其注入组件或引导后(如

bootstrap(AppComponent, [
    HTTP_PROVIDERS, 
    provide(XHRBackend, {useClass: MockBackend}),
    provide(JSONPBackend, {useClass: MockBackend})])
.then((componentRef: ComponentRef) => {
  let injector = componentRef.injector;
  let backend = injector.get(MockBackend);
  backend.connections.subscribe(connection => {
    if(connection.request ...) {
      connection.mockRespond(new Response('awesome'));      
    }
  });
});