MockBackend

A mock backend for testing the Httpservice.

查看"说明"...

已弃用: see https://angular.io/guide/http

      
      class MockBackend implements ConnectionBackend {
  connections: any
  connectionsArray: MockConnection[]
  pendingConnections: any
  verifyNoPendingRequests()
  resolveAllConnections()
  createConnection(req: Request): MockConnection
}
    

说明

This class can be injected in tests, and should be used to override providers to other backends, such as XHRBackend.

属性

属性说明
connections: any EventEmitter

of MockConnectioninstances that have been created by this backend. Can be subscribed to in order to respond to connections.

This property only exists in the mock implementation, not in real Backends.

connectionsArray: MockConnection[]

An array representation of connections. This array will be updated with each connection that is created by this backend.

This property only exists in the mock implementation, not in real Backends.

pendingConnections: any EventEmitter

of MockConnectioninstances that haven't yet been resolved (i.e. with a readyState less than 4). Used internally to verify that no connections are pending via the verifyNoPendingRequests method.

This property only exists in the mock implementation, not in real Backends.

方法

Checks all connections, and raises an exception if any connection has not received a response.

verifyNoPendingRequests()
      
      verifyNoPendingRequests()
    
参数

没有参数。

This method only exists in the mock implementation, not in real Backends.

Can be used in conjunction with verifyNoPendingRequests to resolve any not-yet-resolve connections, if it's expected that there are connections that have not yet received a response.

resolveAllConnections()
      
      resolveAllConnections()
    
参数

没有参数。

This method only exists in the mock implementation, not in real Backends.

Creates a new MockConnection. This is equivalent to calling new MockConnection(), except that it also will emit the new Connection to the connections emitter of this MockBackend instance. This method will usually only be used by tests against the framework itself, not by end-users.

createConnection(req: Request): MockConnection
      
      createConnection(req: Request): MockConnection
    
参数
req Request
返回值

MockConnection

使用说明

Example

import {Injectable, Injector} from '@angular/core'; import {async, fakeAsync, tick} from '@angular/core/testing'; import {BaseRequestOptions, ConnectionBackend, Http, RequestOptions} from '@angular/http'; import {Response, ResponseOptions} from '@angular/http'; import {MockBackend, MockConnection} from '@angular/http/testing'; const HERO_ONE = 'HeroNrOne'; const HERO_TWO = 'WillBeAlwaysTheSecond'; @Injectable() class HeroService { constructor(private http: Http) {} getHeroes(): Promise<String[]> { return this.http.get('myservices.de/api/heroes') .toPromise() .then(response => response.json().data) .catch(e => this.handleError(e)); } private handleError(error: any): Promise<any> { console.error('An error occurred', error); return Promise.reject(error.message || error); } } describe('MockBackend HeroService Example', () => { beforeEach(() => { this.injector = Injector.create([ {provide: ConnectionBackend, useClass: MockBackend}, {provide: RequestOptions, useClass: BaseRequestOptions}, Http, HeroService, ]); this.heroService = this.injector.get(HeroService); this.backend = this.injector.get(ConnectionBackend) as MockBackend; this.backend.connections.subscribe((connection: any) => this.lastConnection = connection); }); it('getHeroes() should query current service url', () => { this.heroService.getHeroes(); expect(this.lastConnection).toBeDefined('no http service connection at all?'); expect(this.lastConnection.request.url).toMatch(/api\/heroes$/, 'url invalid'); }); it('getHeroes() should return some heroes', fakeAsync(() => { let result: String[]; this.heroService.getHeroes().then((heroes: String[]) => result = heroes); this.lastConnection.mockRespond(new Response(new ResponseOptions({ body: JSON.stringify({data: [HERO_ONE, HERO_TWO]}), }))); tick(); expect(result.length).toEqual(2, 'should contain given amount of heroes'); expect(result[0]).toEqual(HERO_ONE, ' HERO_ONE should be the first hero'); expect(result[1]).toEqual(HERO_TWO, ' HERO_TWO should be the second hero'); })); it('getHeroes() while server is down', fakeAsync(() => { let result: String[]; let catchedError: any; this.heroService.getHeroes() .then((heroes: String[]) => result = heroes) .catch((error: any) => catchedError = error); this.lastConnection.mockError(new Response(new ResponseOptions({ status: 404, statusText: 'URL not Found', }))); tick(); expect(result).toBeUndefined(); expect(catchedError).toBeDefined(); })); });
      
      
  1. import {Injectable, Injector} from '@angular/core';
  2. import {async, fakeAsync, tick} from '@angular/core/testing';
  3. import {BaseRequestOptions, ConnectionBackend, Http, RequestOptions} from '@angular/http';
  4. import {Response, ResponseOptions} from '@angular/http';
  5. import {MockBackend, MockConnection} from '@angular/http/testing';
  6.  
  7. const HERO_ONE = 'HeroNrOne';
  8. const HERO_TWO = 'WillBeAlwaysTheSecond';
  9.  
  10. @Injectable()
  11. class HeroService {
  12. constructor(private http: Http) {}
  13.  
  14. getHeroes(): Promise<String[]> {
  15. return this.http.get('myservices.de/api/heroes')
  16. .toPromise()
  17. .then(response => response.json().data)
  18. .catch(e => this.handleError(e));
  19. }
  20.  
  21. private handleError(error: any): Promise<any> {
  22. console.error('An error occurred', error);
  23. return Promise.reject(error.message || error);
  24. }
  25. }
  26.  
  27. describe('MockBackend HeroService Example', () => {
  28. beforeEach(() => {
  29. this.injector = Injector.create([
  30. {provide: ConnectionBackend, useClass: MockBackend},
  31. {provide: RequestOptions, useClass: BaseRequestOptions},
  32. Http,
  33. HeroService,
  34. ]);
  35. this.heroService = this.injector.get(HeroService);
  36. this.backend = this.injector.get(ConnectionBackend) as MockBackend;
  37. this.backend.connections.subscribe((connection: any) => this.lastConnection = connection);
  38. });
  39.  
  40. it('getHeroes() should query current service url', () => {
  41. this.heroService.getHeroes();
  42. expect(this.lastConnection).toBeDefined('no http service connection at all?');
  43. expect(this.lastConnection.request.url).toMatch(/api\/heroes$/, 'url invalid');
  44. });
  45.  
  46. it('getHeroes() should return some heroes', fakeAsync(() => {
  47. let result: String[];
  48. this.heroService.getHeroes().then((heroes: String[]) => result = heroes);
  49. this.lastConnection.mockRespond(new Response(new ResponseOptions({
  50. body: JSON.stringify({data: [HERO_ONE, HERO_TWO]}),
  51. })));
  52. tick();
  53. expect(result.length).toEqual(2, 'should contain given amount of heroes');
  54. expect(result[0]).toEqual(HERO_ONE, ' HERO_ONE should be the first hero');
  55. expect(result[1]).toEqual(HERO_TWO, ' HERO_TWO should be the second hero');
  56. }));
  57.  
  58. it('getHeroes() while server is down', fakeAsync(() => {
  59. let result: String[];
  60. let catchedError: any;
  61. this.heroService.getHeroes()
  62. .then((heroes: String[]) => result = heroes)
  63. .catch((error: any) => catchedError = error);
  64. this.lastConnection.mockError(new Response(new ResponseOptions({
  65. status: 404,
  66. statusText: 'URL not Found',
  67. })));
  68. tick();
  69. expect(result).toBeUndefined();
  70. expect(catchedError).toBeDefined();
  71. }));
  72. });