A mock backend for testing the Http
service.
说明 This class can be injected in tests, and should be used to override providers to other backends, such as XHRBackend
.
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.mockRespond(new Response (new ResponseOptions ({ status: 404, statusText: 'URL not Found', }))); tick (); expect(result).toBeUndefined(); expect(catchedError).toBeDefined(); })); }); This method only exists in the mock implementation, not in real Backends.
属性 属性名 类型 说明 connectionsany
EventEmitter
of MockConnection
instances that have been created by this backend. Can be subscribed to in order to respond to connections.
Example import {Injector } from '@angular/core'; import {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'; it('should get a response', fakeAsync (() => { let connection: MockConnection ; // this will be set when a new connection is emitted from the // backend. let text: string; // this will be set from mock response let injector = Injector.create([ {provide: ConnectionBackend , useClass: MockBackend }, {provide: RequestOptions , useClass: BaseRequestOptions }, Http , ]); let backend = injector.get(ConnectionBackend ); let http = injector.get(Http ); backend.connections.subscribe((c: MockConnection ) => connection = c); http.request('something.json').toPromise().then((res: any) => text = res.text()); connection.mockRespond(new Response (new ResponseOptions ({body: 'Something'}))); tick (); expect(text).toBe('Something'); })); This property only exists in the mock implementation, not in real Backends.
connectionsArrayMockConnection []
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.
pendingConnectionsany
EventEmitter
of MockConnection
instances 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.
方法 verifyNoPendingRequests() Checks all connections, and raises an exception if any connection has not received a response.
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() 参数 没有参数。
This method only exists in the mock implementation, not in real Backends.