1
|
/**
|
2
|
* @license Angular v4.4.6
|
3
|
* (c) 2010-2017 Google, Inc. https://angular.io/
|
4
|
* License: MIT
|
5
|
*/
|
6
|
import { Injectable } from '@angular/core';
|
7
|
import { ReadyState, Request } from '@angular/http';
|
8
|
import { ReplaySubject } from 'rxjs/ReplaySubject';
|
9
|
import { Subject } from 'rxjs/Subject';
|
10
|
import { take } from 'rxjs/operator/take';
|
11
|
|
12
|
/**
|
13
|
* @license
|
14
|
* Copyright Google Inc. All Rights Reserved.
|
15
|
*
|
16
|
* Use of this source code is governed by an MIT-style license that can be
|
17
|
* found in the LICENSE file at https://angular.io/license
|
18
|
*/
|
19
|
/**
|
20
|
*
|
21
|
* Mock Connection to represent a {\@link Connection} for tests.
|
22
|
*
|
23
|
* \@experimental
|
24
|
*/
|
25
|
class MockConnection {
|
26
|
/**
|
27
|
* @param {?} req
|
28
|
*/
|
29
|
constructor(req) {
|
30
|
this.response = take.call(new ReplaySubject(1), 1);
|
31
|
this.readyState = ReadyState.Open;
|
32
|
this.request = req;
|
33
|
}
|
34
|
/**
|
35
|
* Sends a mock response to the connection. This response is the value that is emitted to the
|
36
|
* {\@link EventEmitter} returned by {\@link Http}.
|
37
|
*
|
38
|
* ### Example
|
39
|
*
|
40
|
* ```
|
41
|
* var connection;
|
42
|
* backend.connections.subscribe(c => connection = c);
|
43
|
* http.request('data.json').subscribe(res => console.log(res.text()));
|
44
|
* connection.mockRespond(new Response(new ResponseOptions({ body: 'fake response' }))); //logs
|
45
|
* 'fake response'
|
46
|
* ```
|
47
|
*
|
48
|
* @param {?} res
|
49
|
* @return {?}
|
50
|
*/
|
51
|
mockRespond(res) {
|
52
|
if (this.readyState === ReadyState.Done || this.readyState === ReadyState.Cancelled) {
|
53
|
throw new Error('Connection has already been resolved');
|
54
|
}
|
55
|
this.readyState = ReadyState.Done;
|
56
|
this.response.next(res);
|
57
|
this.response.complete();
|
58
|
}
|
59
|
/**
|
60
|
* Not yet implemented!
|
61
|
*
|
62
|
* Sends the provided {\@link Response} to the `downloadObserver` of the `Request`
|
63
|
* associated with this connection.
|
64
|
* @param {?} res
|
65
|
* @return {?}
|
66
|
*/
|
67
|
mockDownload(res) {
|
68
|
// this.request.downloadObserver.onNext(res);
|
69
|
// if (res.bytesLoaded === res.totalBytes) {
|
70
|
// this.request.downloadObserver.onCompleted();
|
71
|
// }
|
72
|
}
|
73
|
/**
|
74
|
* Emits the provided error object as an error to the {\@link Response} {\@link EventEmitter}
|
75
|
* returned
|
76
|
* from {\@link Http}.
|
77
|
*
|
78
|
* ### Example
|
79
|
*
|
80
|
* ```
|
81
|
* var connection;
|
82
|
* backend.connections.subscribe(c => connection = c);
|
83
|
* http.request('data.json').subscribe(res => res, err => console.log(err)));
|
84
|
* connection.mockError(new Error('error'));
|
85
|
* ```
|
86
|
*
|
87
|
* @param {?=} err
|
88
|
* @return {?}
|
89
|
*/
|
90
|
mockError(err) {
|
91
|
// Matches ResourceLoader semantics
|
92
|
this.readyState = ReadyState.Done;
|
93
|
this.response.error(err);
|
94
|
}
|
95
|
}
|
96
|
/**
|
97
|
* A mock backend for testing the {\@link Http} service.
|
98
|
*
|
99
|
* This class can be injected in tests, and should be used to override providers
|
100
|
* to other backends, such as {\@link XHRBackend}.
|
101
|
*
|
102
|
* ### Example
|
103
|
*
|
104
|
* ```
|
105
|
* import {Injectable, ReflectiveInjector} from '\@angular/core';
|
106
|
* import {async, fakeAsync, tick} from '\@angular/core/testing';
|
107
|
* import {BaseRequestOptions, ConnectionBackend, Http, RequestOptions} from '\@angular/http';
|
108
|
* import {Response, ResponseOptions} from '\@angular/http';
|
109
|
* import {MockBackend, MockConnection} from '\@angular/http/testing';
|
110
|
*
|
111
|
* const HERO_ONE = 'HeroNrOne';
|
112
|
* const HERO_TWO = 'WillBeAlwaysTheSecond';
|
113
|
*
|
114
|
* \@Injectable()
|
115
|
* class HeroService {
|
116
|
* constructor(private http: Http) {}
|
117
|
*
|
118
|
* getHeroes(): Promise<String[]> {
|
119
|
* return this.http.get('myservices.de/api/heroes')
|
120
|
* .toPromise()
|
121
|
* .then(response => response.json().data)
|
122
|
* .catch(e => this.handleError(e));
|
123
|
* }
|
124
|
*
|
125
|
* private handleError(error: any): Promise<any> {
|
126
|
* console.error('An error occurred', error);
|
127
|
* return Promise.reject(error.message || error);
|
128
|
* }
|
129
|
* }
|
130
|
*
|
131
|
* describe('MockBackend HeroService Example', () => {
|
132
|
* beforeEach(() => {
|
133
|
* this.injector = ReflectiveInjector.resolveAndCreate([
|
134
|
* {provide: ConnectionBackend, useClass: MockBackend},
|
135
|
* {provide: RequestOptions, useClass: BaseRequestOptions},
|
136
|
* Http,
|
137
|
* HeroService,
|
138
|
* ]);
|
139
|
* this.heroService = this.injector.get(HeroService);
|
140
|
* this.backend = this.injector.get(ConnectionBackend) as MockBackend;
|
141
|
* this.backend.connections.subscribe((connection: any) => this.lastConnection = connection);
|
142
|
* });
|
143
|
*
|
144
|
* it('getHeroes() should query current service url', () => {
|
145
|
* this.heroService.getHeroes();
|
146
|
* expect(this.lastConnection).toBeDefined('no http service connection at all?');
|
147
|
* expect(this.lastConnection.request.url).toMatch(/api\/heroes$/, 'url invalid');
|
148
|
* });
|
149
|
*
|
150
|
* it('getHeroes() should return some heroes', fakeAsync(() => {
|
151
|
* let result: String[];
|
152
|
* this.heroService.getHeroes().then((heroes: String[]) => result = heroes);
|
153
|
* this.lastConnection.mockRespond(new Response(new ResponseOptions({
|
154
|
* body: JSON.stringify({data: [HERO_ONE, HERO_TWO]}),
|
155
|
* })));
|
156
|
* tick();
|
157
|
* expect(result.length).toEqual(2, 'should contain given amount of heroes');
|
158
|
* expect(result[0]).toEqual(HERO_ONE, ' HERO_ONE should be the first hero');
|
159
|
* expect(result[1]).toEqual(HERO_TWO, ' HERO_TWO should be the second hero');
|
160
|
* }));
|
161
|
*
|
162
|
* it('getHeroes() while server is down', fakeAsync(() => {
|
163
|
* let result: String[];
|
164
|
* let catchedError: any;
|
165
|
* this.heroService.getHeroes()
|
166
|
* .then((heroes: String[]) => result = heroes)
|
167
|
* .catch((error: any) => catchedError = error);
|
168
|
* this.lastConnection.mockRespond(new Response(new ResponseOptions({
|
169
|
* status: 404,
|
170
|
* statusText: 'URL not Found',
|
171
|
* })));
|
172
|
* tick();
|
173
|
* expect(result).toBeUndefined();
|
174
|
* expect(catchedError).toBeDefined();
|
175
|
* }));
|
176
|
* });
|
177
|
* ```
|
178
|
*
|
179
|
* This method only exists in the mock implementation, not in real Backends.
|
180
|
*
|
181
|
* \@experimental
|
182
|
*/
|
183
|
class MockBackend {
|
184
|
constructor() {
|
185
|
this.connectionsArray = [];
|
186
|
this.connections = new Subject();
|
187
|
this.connections.subscribe((connection) => this.connectionsArray.push(connection));
|
188
|
this.pendingConnections = new Subject();
|
189
|
}
|
190
|
/**
|
191
|
* Checks all connections, and raises an exception if any connection has not received a response.
|
192
|
*
|
193
|
* This method only exists in the mock implementation, not in real Backends.
|
194
|
* @return {?}
|
195
|
*/
|
196
|
verifyNoPendingRequests() {
|
197
|
let /** @type {?} */ pending = 0;
|
198
|
this.pendingConnections.subscribe((c) => pending++);
|
199
|
if (pending > 0)
|
200
|
throw new Error(`${pending} pending connections to be resolved`);
|
201
|
}
|
202
|
/**
|
203
|
* Can be used in conjunction with `verifyNoPendingRequests` to resolve any not-yet-resolve
|
204
|
* connections, if it's expected that there are connections that have not yet received a response.
|
205
|
*
|
206
|
* This method only exists in the mock implementation, not in real Backends.
|
207
|
* @return {?}
|
208
|
*/
|
209
|
resolveAllConnections() { this.connections.subscribe((c) => c.readyState = 4); }
|
210
|
/**
|
211
|
* Creates a new {\@link MockConnection}. This is equivalent to calling `new
|
212
|
* MockConnection()`, except that it also will emit the new `Connection` to the `connections`
|
213
|
* emitter of this `MockBackend` instance. This method will usually only be used by tests
|
214
|
* against the framework itself, not by end-users.
|
215
|
* @param {?} req
|
216
|
* @return {?}
|
217
|
*/
|
218
|
createConnection(req) {
|
219
|
if (!req || !(req instanceof Request)) {
|
220
|
throw new Error(`createConnection requires an instance of Request, got ${req}`);
|
221
|
}
|
222
|
const /** @type {?} */ connection = new MockConnection(req);
|
223
|
this.connections.next(connection);
|
224
|
return connection;
|
225
|
}
|
226
|
}
|
227
|
MockBackend.decorators = [
|
228
|
{ type: Injectable },
|
229
|
];
|
230
|
/**
|
231
|
* @nocollapse
|
232
|
*/
|
233
|
MockBackend.ctorParameters = () => [];
|
234
|
|
235
|
/**
|
236
|
* @license
|
237
|
* Copyright Google Inc. All Rights Reserved.
|
238
|
*
|
239
|
* Use of this source code is governed by an MIT-style license that can be
|
240
|
* found in the LICENSE file at https://angular.io/license
|
241
|
*/
|
242
|
/**
|
243
|
* @module
|
244
|
* @description
|
245
|
* Entry point for all public APIs of the platform-server/testing package.
|
246
|
*/
|
247
|
|
248
|
/**
|
249
|
* @license
|
250
|
* Copyright Google Inc. All Rights Reserved.
|
251
|
*
|
252
|
* Use of this source code is governed by an MIT-style license that can be
|
253
|
* found in the LICENSE file at https://angular.io/license
|
254
|
*/
|
255
|
/**
|
256
|
* @module
|
257
|
* @description
|
258
|
* Entry point for all public APIs of the http testing package.
|
259
|
*/
|
260
|
|
261
|
/**
|
262
|
* Generated bundle index. Do not edit.
|
263
|
*/
|
264
|
|
265
|
export { MockConnection, MockBackend };
|
266
|
//# sourceMappingURL=testing.js.map
|