Skip to content

Commit 1e6440e

Browse files
e-heinhansl
authored andcommitted
docs(Http): fix and extend samples for testing/MockBackend (angular#13689)
Fix samples for MockBackend and MockBackend.connections that were outdated. Also extend central sample for MockBackend to ease getting started.
1 parent 6b02b80 commit 1e6440e

1 file changed

Lines changed: 94 additions & 38 deletions

File tree

modules/@angular/http/testing/mock_backend.ts

Lines changed: 94 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -114,25 +114,78 @@ export class MockConnection implements Connection {
114114
* ### Example
115115
*
116116
* ```
117-
* import {BaseRequestOptions, Http} from '@angular/http';
118-
* import {MockBackend} from '@angular/http/testing';
119-
* it('should get some data', inject([AsyncTestCompleter], (async) => {
120-
* var connection;
121-
* var injector = Injector.resolveAndCreate([
122-
* MockBackend,
123-
* {provide: Http, useFactory: (backend, options) => {
124-
* return new Http(backend, options);
125-
* }, deps: [MockBackend, BaseRequestOptions]}]);
126-
* var http = injector.get(Http);
127-
* var backend = injector.get(MockBackend);
128-
* //Assign any newly-created connection to local variable
129-
* backend.connections.subscribe(c => connection = c);
130-
* http.request('data.json').subscribe((res) => {
131-
* expect(res.text()).toBe('awesome');
132-
* async.done();
117+
* import {Injectable, ReflectiveInjector} from '@angular/core';
118+
* import {async, fakeAsync, tick} from '@angular/core/testing';
119+
* import {BaseRequestOptions, ConnectionBackend, Http, RequestOptions} from '@angular/http';
120+
* import {Response, ResponseOptions} from '@angular/http';
121+
* import {MockBackend, MockConnection} from '@angular/http/testing';
122+
*
123+
* const HERO_ONE = 'HeroNrOne';
124+
* const HERO_TWO = 'WillBeAlwaysTheSecond';
125+
*
126+
* @Injectable()
127+
* class HeroService {
128+
* constructor(private http: Http) {}
129+
*
130+
* getHeroes(): Promise<String[]> {
131+
* return this.http.get('myservices.de/api/heroes')
132+
* .toPromise()
133+
* .then(response => response.json().data)
134+
* .catch(e => this.handleError(e));
135+
* }
136+
*
137+
* private handleError(error: any): Promise<any> {
138+
* console.error('An error occurred', error);
139+
* return Promise.reject(error.message || error);
140+
* }
141+
* }
142+
*
143+
* describe('MockBackend HeroService Example', () => {
144+
* beforeEach(() => {
145+
* this.injector = ReflectiveInjector.resolveAndCreate([
146+
* {provide: ConnectionBackend, useClass: MockBackend},
147+
* {provide: RequestOptions, useClass: BaseRequestOptions},
148+
* Http,
149+
* HeroService,
150+
* ]);
151+
* this.heroService = this.injector.get(HeroService);
152+
* this.backend = this.injector.get(ConnectionBackend) as MockBackend;
153+
* this.backend.connections.subscribe((connection: any) => this.lastConnection = connection);
133154
* });
134-
* connection.mockRespond(new Response('awesome'));
135-
* }));
155+
*
156+
* it('getHeroes() should query current service url', () => {
157+
* this.heroService.getHeroes();
158+
* expect(this.lastConnection).toBeDefined('no http service connection at all?');
159+
* expect(this.lastConnection.request.url).toMatch(/api\/heroes$/, 'url invalid');
160+
* });
161+
*
162+
* it('getHeroes() should return some heroes', fakeAsync(() => {
163+
* let result: String[];
164+
* this.heroService.getHeroes().then((heroes: String[]) => result = heroes);
165+
* this.lastConnection.mockRespond(new Response(new ResponseOptions({
166+
* body: JSON.stringify({data: [HERO_ONE, HERO_TWO]}),
167+
* })));
168+
* tick();
169+
* expect(result.length).toEqual(2, 'should contain given amount of heroes');
170+
* expect(result[0]).toEqual(HERO_ONE, ' HERO_ONE should be the first hero');
171+
* expect(result[1]).toEqual(HERO_TWO, ' HERO_TWO should be the second hero');
172+
* }));
173+
*
174+
* it('getHeroes() while server is down', fakeAsync(() => {
175+
* let result: String[];
176+
* let catchedError: any;
177+
* this.heroService.getHeroes()
178+
* .then((heroes: String[]) => result = heroes)
179+
* .catch((error: any) => catchedError = error);
180+
* this.lastConnection.mockRespond(new Response(new ResponseOptions({
181+
* status: 404,
182+
* statusText: 'URL not Found',
183+
* })));
184+
* tick();
185+
* expect(result).toBeUndefined();
186+
* expect(catchedError).toBeDefined();
187+
* }));
188+
* });
136189
* ```
137190
*
138191
* This method only exists in the mock implementation, not in real Backends.
@@ -149,27 +202,30 @@ export class MockBackend implements ConnectionBackend {
149202
* ### Example
150203
*
151204
* ```
152-
* import {Http, BaseRequestOptions, Response} from '@angular/http';
153-
* import {MockBackend} from '@angular/http/testing';
154-
* import {Injector, provide} from '@angular/core';
205+
* import {ReflectiveInjector} from '@angular/core';
206+
* import {fakeAsync, tick} from '@angular/core/testing';
207+
* import {BaseRequestOptions, ConnectionBackend, Http, RequestOptions} from '@angular/http';
208+
* import {Response, ResponseOptions} from '@angular/http';
209+
* import {MockBackend, MockConnection} from '@angular/http/testing';
155210
*
156-
* it('should get a response', () => {
157-
* var connection; //this will be set when a new connection is emitted from the backend.
158-
* var text; //this will be set from mock response
159-
* var injector = Injector.resolveAndCreate([
160-
* MockBackend,
161-
* {provide: Http, useFactory: (backend, options) => {
162-
* return new Http(backend, options);
163-
* }, deps: [MockBackend, BaseRequestOptions]}]);
164-
* var backend = injector.get(MockBackend);
165-
* var http = injector.get(Http);
166-
* backend.connections.subscribe(c => connection = c);
167-
* http.request('something.json').subscribe(res => {
168-
* text = res.text();
169-
* });
170-
* connection.mockRespond(new Response({body: 'Something'}));
171-
* expect(text).toBe('Something');
172-
* });
211+
* it('should get a response', fakeAsync(() => {
212+
* let connection:
213+
* MockConnection; // this will be set when a new connection is emitted from the
214+
* // backend.
215+
* let text: string; // this will be set from mock response
216+
* let injector = ReflectiveInjector.resolveAndCreate([
217+
* {provide: ConnectionBackend, useClass: MockBackend},
218+
* {provide: RequestOptions, useClass: BaseRequestOptions},
219+
* Http,
220+
* ]);
221+
* let backend = injector.get(ConnectionBackend);
222+
* let http = injector.get(Http);
223+
* backend.connections.subscribe((c: MockConnection) => connection = c);
224+
* http.request('something.json').toPromise().then((res: any) => text = res.text());
225+
* connection.mockRespond(new Response(new ResponseOptions({body: 'Something'})));
226+
* tick();
227+
* expect(text).toBe('Something');
228+
* }));
173229
* ```
174230
*
175231
* This property only exists in the mock implementation, not in real Backends.

0 commit comments

Comments
 (0)