Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(Http): fix and extend samples for testing/MockBackend #13689

Merged
merged 1 commit into from
Dec 29, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
132 changes: 94 additions & 38 deletions modules/@angular/http/testing/mock_backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,25 +114,78 @@ export class MockConnection implements Connection {
* ### Example
*
* ```
* import {BaseRequestOptions, Http} from '@angular/http';
* import {MockBackend} from '@angular/http/testing';
* it('should get some data', inject([AsyncTestCompleter], (async) => {
* var connection;
* var injector = Injector.resolveAndCreate([
* MockBackend,
* {provide: Http, useFactory: (backend, options) => {
* return new Http(backend, options);
* }, deps: [MockBackend, BaseRequestOptions]}]);
* 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();
* import {Injectable, ReflectiveInjector} 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()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we also use observables instead of promises?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tried observable and subscribe first. Didn't work. Then I switched to promise according to other samples ... worked - don't understand why. I'd preferred the observable, too.

* .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 = ReflectiveInjector.resolveAndCreate([
* {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);
* });
* connection.mockRespond(new Response('awesome'));
* }));
*
* 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.
Expand All @@ -149,27 +202,30 @@ export class MockBackend implements ConnectionBackend {
* ### Example
*
* ```
* import {Http, BaseRequestOptions, Response} from '@angular/http';
* import {MockBackend} from '@angular/http/testing';
* import {Injector, provide} from '@angular/core';
* import {ReflectiveInjector} 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', () => {
* var connection; //this will be set when a new connection is emitted from the backend.
* var text; //this will be set from mock response
* var injector = Injector.resolveAndCreate([
* MockBackend,
* {provide: Http, useFactory: (backend, options) => {
* return new Http(backend, options);
* }, deps: [MockBackend, BaseRequestOptions]}]);
* var backend = injector.get(MockBackend);
* var http = injector.get(Http);
* backend.connections.subscribe(c => connection = c);
* http.request('something.json').subscribe(res => {
* text = res.text();
* });
* connection.mockRespond(new Response({body: 'Something'}));
* expect(text).toBe('Something');
* });
* 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 = ReflectiveInjector.resolveAndCreate([
* {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.
Expand Down