chore(http): make all typings explicit

This commit is contained in:
Jeff Cross 2016-02-01 17:05:50 -08:00 committed by Alex Eagle
parent da1fcfd820
commit f2c7946cca
14 changed files with 203 additions and 163 deletions

View File

@ -156,7 +156,8 @@ export const HTTP_PROVIDERS: any[] = [
// issue: https://github.com/angular/angular/issues/3183
provide(Http,
{
useFactory: (xhrBackend, requestOptions) => new Http(xhrBackend, requestOptions),
useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) =>
new Http(xhrBackend, requestOptions),
deps: [XHRBackend, RequestOptions]
}),
BrowserXhr,
@ -283,7 +284,8 @@ export const JSONP_PROVIDERS: any[] = [
// issue: https://github.com/angular/angular/issues/3183
provide(Jsonp,
{
useFactory: (jsonpBackend, requestOptions) => new Jsonp(jsonpBackend, requestOptions),
useFactory: (jsonpBackend: JSONPBackend, requestOptions: RequestOptions) =>
new Jsonp(jsonpBackend, requestOptions),
deps: [JSONPBackend, RequestOptions]
}),
BrowserJsonp,

View File

@ -3,11 +3,11 @@ import {global} from 'angular2/src/facade/lang';
let _nextRequestId = 0;
export const JSONP_HOME = '__ng_jsonp__';
var _jsonpConnections = null;
var _jsonpConnections: {[key: string]: any} = null;
function _getJsonpConnections(): {[key: string]: any} {
if (_jsonpConnections === null) {
_jsonpConnections = global[JSONP_HOME] = {};
_jsonpConnections = (<{[key: string]: any}>global)[JSONP_HOME] = {};
}
return _jsonpConnections;
}

View File

@ -8,6 +8,7 @@ import {BrowserJsonp} from './browser_jsonp';
import {makeTypeError} from 'angular2/src/facade/exceptions';
import {StringWrapper, isPresent} from 'angular2/src/facade/lang';
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
const JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.';
const JSONP_ERR_WRONG_METHOD = 'JSONP requests must use GET request method.';
@ -51,7 +52,7 @@ export class JSONPConnection_ extends JSONPConnection {
throw makeTypeError(JSONP_ERR_WRONG_METHOD);
}
this.request = req;
this.response = new Observable(responseObserver => {
this.response = new Observable((responseObserver: Observer<Response>) => {
this.readyState = ReadyState.Loading;
let id = this._id = _dom.nextRequestID();
@ -70,7 +71,7 @@ export class JSONPConnection_ extends JSONPConnection {
let script = this._script = _dom.build(url);
let onLoad = event => {
let onLoad = (event: Event) => {
if (this.readyState === ReadyState.Cancelled) return;
this.readyState = ReadyState.Done;
_dom.cleanup(script);
@ -93,7 +94,7 @@ export class JSONPConnection_ extends JSONPConnection {
responseObserver.complete();
};
let onError = error => {
let onError = (error: Error) => {
if (this.readyState === ReadyState.Cancelled) return;
this.readyState = ReadyState.Done;
_dom.cleanup(script);

View File

@ -32,7 +32,7 @@ export class MockConnection implements Connection {
* {@link EventEmitter} of {@link Response}. Can be subscribed to in order to be notified when a
* response is available.
*/
response: any; // Subject<Response>
response: ReplaySubject<Response>;
constructor(req: Request) {
this.response = take.call(new ReplaySubject(1), 1);
@ -176,7 +176,8 @@ export class MockBackend implements ConnectionBackend {
constructor() {
this.connectionsArray = [];
this.connections = new Subject();
this.connections.subscribe(connection => this.connectionsArray.push(connection));
this.connections.subscribe((connection: MockConnection) =>
this.connectionsArray.push(connection));
this.pendingConnections = new Subject();
}
@ -187,7 +188,7 @@ export class MockBackend implements ConnectionBackend {
*/
verifyNoPendingRequests() {
let pending = 0;
this.pendingConnections.subscribe(c => pending++);
this.pendingConnections.subscribe((c: MockConnection) => pending++);
if (pending > 0) throw new BaseException(`${pending} pending connections to be resolved`);
}
@ -197,7 +198,7 @@ export class MockBackend implements ConnectionBackend {
*
* This method only exists in the mock implementation, not in real Backends.
*/
resolveAllConnections() { this.connections.subscribe(c => c.readyState = 4); }
resolveAllConnections() { this.connections.subscribe((c: MockConnection) => c.readyState = 4); }
/**
* Creates a new {@link MockConnection}. This is equivalent to calling `new
@ -205,7 +206,7 @@ export class MockBackend implements ConnectionBackend {
* 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): Connection {
createConnection(req: Request): MockConnection {
if (!isPresent(req) || !(req instanceof Request)) {
throw new BaseException(`createConnection requires an instance of Request, got ${req}`);
}

View File

@ -8,7 +8,9 @@ import {Injectable} from 'angular2/core';
import {BrowserXhr} from './browser_xhr';
import {isPresent} from 'angular2/src/facade/lang';
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
import {isSuccess, getResponseURL} from '../http_utils';
/**
* Creates connections using `XMLHttpRequest`. Given a fully-qualified
* request, an `XHRConnection` will immediately create an `XMLHttpRequest` object and send the
@ -27,7 +29,7 @@ export class XHRConnection implements Connection {
readyState: ReadyState;
constructor(req: Request, browserXHR: BrowserXhr, baseResponseOptions?: ResponseOptions) {
this.request = req;
this.response = new Observable(responseObserver => {
this.response = new Observable((responseObserver: Observer<Response>) => {
let _xhr: XMLHttpRequest = browserXHR.build();
_xhr.open(RequestMethod[req.method].toUpperCase(), req.url);
// load event handler
@ -64,7 +66,7 @@ export class XHRConnection implements Connection {
responseObserver.error(response);
};
// error event handler
let onError = (err) => {
let onError = (err: any) => {
var responseOptions = new ResponseOptions({body: err, type: ResponseType.Error});
if (isPresent(baseResponseOptions)) {
responseOptions = baseResponseOptions.merge(responseOptions);

View File

@ -57,8 +57,9 @@ export class Headers {
}
// headers instanceof StringMap
StringMapWrapper.forEach(
headers, (v, k) => { this._headersMap.set(k, isListLikeIterable(v) ? v : [v]); });
StringMapWrapper.forEach(headers, (v: any, k: string) => {
this._headersMap.set(k, isListLikeIterable(v) ? v : [v]);
});
}
/**
@ -110,13 +111,13 @@ export class Headers {
* Sets or overrides header value for given name.
*/
set(header: string, value: string | string[]): void {
var list = [];
var list: string[] = [];
if (isListLikeIterable(value)) {
var pushValue = (<string[]>value).join(',');
list.push(pushValue);
} else {
list.push(value);
list.push(<string>value);
}
this._headersMap.set(header, list);

View File

@ -12,7 +12,8 @@ function httpRequest(backend: ConnectionBackend, request: Request): Observable<R
return backend.createConnection(request).response;
}
function mergeOptions(defaultOpts, providedOpts, method, url): RequestOptions {
function mergeOptions(defaultOpts: BaseRequestOptions, providedOpts: RequestOptionsArgs,
method: RequestMethod, url: string): RequestOptions {
var newOptions = defaultOpts;
if (isPresent(providedOpts)) {
// Hack so Dart can used named parameters
@ -104,7 +105,7 @@ export class Http {
if (isString(url)) {
responseObservable = httpRequest(
this._backend,
new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Get, url)));
new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Get, <string>url)));
} else if (url instanceof Request) {
responseObservable = httpRequest(this._backend, url);
} else {
@ -183,7 +184,8 @@ export class Jsonp extends Http {
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
var responseObservable: any;
if (isString(url)) {
url = new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Get, url));
url =
new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Get, <string>url));
}
if (url instanceof Request) {
if (url.method !== RequestMethod.Get) {

View File

@ -3,16 +3,18 @@ import {RequestMethod} from './enums';
import {makeTypeError} from 'angular2/src/facade/exceptions';
import {Response} from './static_response';
export function normalizeMethodName(method): RequestMethod {
export function normalizeMethodName(method: string | RequestMethod): RequestMethod {
if (isString(method)) {
var originalMethod = method;
method = method.replace(/(\w)(\w*)/g, (g0, g1, g2) => g1.toUpperCase() + g2.toLowerCase());
method = RequestMethod[method];
method = (<string>method)
.replace(/(\w)(\w*)/g, (g0: string, g1: string, g2: string) =>
g1.toUpperCase() + g2.toLowerCase());
method = <number>(<{[key: string]: any}>RequestMethod)[method];
if (typeof method !== 'number')
throw makeTypeError(
`Invalid request method. The method "${originalMethod}" is not supported.`);
}
return method;
return <RequestMethod>method;
}
export const isSuccess = (status: number): boolean => (status >= 200 && status < 300);

View File

@ -92,7 +92,7 @@ export class Response {
* Attempts to return body as parsed `JSON` object, or raises an exception.
*/
json(): any {
var jsonResponse;
var jsonResponse: string | Object;
if (isJsObject(this._body)) {
jsonResponse = this._body;
} else if (isString(this._body)) {

View File

@ -121,7 +121,7 @@ export class URLSearchParams {
}
toString(): string {
var paramsList = [];
var paramsList: string[] = [];
this.paramsMap.forEach((values, k) => { values.forEach(v => paramsList.push(k + '=' + v)); });
return paramsList.join('&');
}

View File

@ -29,8 +29,8 @@ import {RequestOptions, BaseRequestOptions} from 'angular2/src/http/base_request
import {BaseResponseOptions, ResponseOptions} from 'angular2/src/http/base_response_options';
import {ResponseType, ReadyState, RequestMethod} from 'angular2/src/http/enums';
var addEventListenerSpy;
var existingScripts = [];
var addEventListenerSpy: any;
var existingScripts: MockBrowserJsonp[] = [];
var unused: Response;
class MockBrowserJsonp extends BrowserJsonp {
@ -67,8 +67,8 @@ class MockBrowserJsonp extends BrowserJsonp {
export function main() {
describe('JSONPBackend', () => {
let backend;
let sampleRequest;
let backend: JSONPBackend_;
let sampleRequest: Request;
beforeEach(() => {
let injector = Injector.resolveAndCreate([
@ -84,7 +84,7 @@ export function main() {
afterEach(() => { existingScripts = []; });
it('should create a connection', () => {
var instance;
var instance: JSONPConnection;
expect(() => instance = backend.createConnection(sampleRequest)).not.toThrow();
expect(instance).toBeAnInstanceOf(JSONPConnection);
});
@ -92,7 +92,7 @@ export function main() {
describe('JSONPConnection', () => {
it('should use the injected BaseResponseOptions to create the response',
inject([AsyncTestCompleter], async => {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
let connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp(),
new ResponseOptions({type: ResponseType.Error}));
connection.response.subscribe(res => {
@ -103,7 +103,8 @@ export function main() {
existingScripts[0].dispatchEvent('load');
}));
it('should ignore load/callback when disposed', inject([AsyncTestCompleter], async => {
it('should ignore load/callback when disposed',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
let spy = new SpyObject();
let loadSpy = spy.spy('load');
@ -126,7 +127,7 @@ export function main() {
}));
it('should report error if loaded without invoking callback',
inject([AsyncTestCompleter], async => {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
let connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
connection.response.subscribe(
res => {
@ -141,7 +142,8 @@ export function main() {
existingScripts[0].dispatchEvent('load');
}));
it('should report error if script contains error', inject([AsyncTestCompleter], async => {
it('should report error if script contains error',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
let connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
connection.response.subscribe(
@ -169,7 +171,8 @@ export function main() {
});
});
it('should respond with data passed to callback', inject([AsyncTestCompleter], async => {
it('should respond with data passed to callback',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
let connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
connection.response.subscribe(res => {

View File

@ -22,16 +22,16 @@ import {Map} from 'angular2/src/facade/collection';
import {RequestOptions, BaseRequestOptions} from 'angular2/src/http/base_request_options';
import {BaseResponseOptions, ResponseOptions} from 'angular2/src/http/base_response_options';
import {ResponseType} from 'angular2/src/http/enums';
import {ReplaySubject} from 'rxjs/subject/ReplaySubject';
export function main() {
describe('MockBackend', () => {
var backend;
var sampleRequest1;
var sampleResponse1;
var sampleRequest2;
var sampleResponse2;
var connection;
var backend: MockBackend;
var sampleRequest1: Request;
var sampleResponse1: Response;
var sampleRequest2: Request;
var sampleResponse2: Response;
beforeEach(() => {
var injector = Injector.resolveAndCreate(
@ -50,47 +50,50 @@ export function main() {
() => {expect(backend.createConnection(sampleRequest1)).toBeAnInstanceOf(MockConnection)});
it('should create a new connection and allow subscription', () => {
let connection = backend.createConnection(sampleRequest1);
let connection: MockConnection = backend.createConnection(sampleRequest1);
connection.response.subscribe(() => {});
});
it('should allow responding after subscription', inject([AsyncTestCompleter], async => {
let connection = backend.createConnection(sampleRequest1);
connection.response.subscribe((res) => { async.done(); });
it('should allow responding after subscription',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
let connection: MockConnection = backend.createConnection(sampleRequest1);
connection.response.subscribe(() => { async.done(); });
connection.mockRespond(sampleResponse1);
}));
it('should allow subscribing after responding', inject([AsyncTestCompleter], async => {
let connection = backend.createConnection(sampleRequest1);
it('should allow subscribing after responding',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
let connection: MockConnection = backend.createConnection(sampleRequest1);
connection.mockRespond(sampleResponse1);
connection.response.subscribe((res) => { async.done(); });
connection.response.subscribe(() => { async.done(); });
}));
it('should allow responding after subscription with an error',
inject([AsyncTestCompleter], async => {
let connection = backend.createConnection(sampleRequest1);
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
let connection: MockConnection = backend.createConnection(sampleRequest1);
connection.response.subscribe(null, () => { async.done(); });
connection.mockError(new Error('nope'));
}));
it('should not throw when there are no unresolved requests',
inject([AsyncTestCompleter], async => {
let connection = backend.createConnection(sampleRequest1);
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
let connection: MockConnection = backend.createConnection(sampleRequest1);
connection.response.subscribe(() => { async.done(); });
connection.mockRespond(sampleResponse1);
backend.verifyNoPendingRequests();
}));
xit('should throw when there are unresolved requests', inject([AsyncTestCompleter], async => {
let connection = backend.createConnection(sampleRequest1);
xit('should throw when there are unresolved requests',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
let connection: MockConnection = backend.createConnection(sampleRequest1);
connection.response.subscribe(() => { async.done(); });
backend.verifyNoPendingRequests();
}));
it('should work when requests are resolved out of order',
inject([AsyncTestCompleter], async => {
let connection1 = backend.createConnection(sampleRequest1);
let connection2 = backend.createConnection(sampleRequest1);
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
let connection1: MockConnection = backend.createConnection(sampleRequest1);
let connection2: MockConnection = backend.createConnection(sampleRequest1);
connection1.response.subscribe(() => { async.done(); });
connection2.response.subscribe(() => {});
connection2.mockRespond(sampleResponse1);
@ -98,10 +101,12 @@ export function main() {
backend.verifyNoPendingRequests();
}));
xit('should allow double subscribing', inject([AsyncTestCompleter], async => {
let responses = [sampleResponse1, sampleResponse2];
backend.connections.subscribe(c => c.mockRespond(responses.shift()));
let responseObservable = backend.createConnection(sampleRequest1).response;
xit('should allow double subscribing',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
let responses: Response[] = [sampleResponse1, sampleResponse2];
backend.connections.subscribe((c: MockConnection) => c.mockRespond(responses.shift()));
let responseObservable: ReplaySubject<Response> =
backend.createConnection(sampleRequest1).response;
responseObservable.subscribe(res => expect(res.text()).toBe('response1'));
responseObservable.subscribe(res => expect(res.text()).toBe('response2'), null,
async.done);

View File

@ -23,12 +23,12 @@ import {RequestOptions, BaseRequestOptions} from 'angular2/src/http/base_request
import {BaseResponseOptions, ResponseOptions} from 'angular2/src/http/base_response_options';
import {ResponseType} from 'angular2/src/http/enums';
var abortSpy;
var sendSpy;
var openSpy;
var setRequestHeaderSpy;
var addEventListenerSpy;
var existingXHRs = [];
var abortSpy: any;
var sendSpy: any;
var openSpy: any;
var setRequestHeaderSpy: any;
var addEventListenerSpy: any;
var existingXHRs: MockBrowserXHR[] = [];
var unused: Response;
class MockBrowserXHR extends BrowserXhr {
@ -51,19 +51,21 @@ class MockBrowserXHR extends BrowserXhr {
this.setRequestHeader = setRequestHeaderSpy = spy.spy('setRequestHeader');
}
setStatusCode(status) { this.status = status; }
setStatusCode(status: number) { this.status = status; }
setResponse(value) { this.response = value; }
setResponse(value: string) { this.response = value; }
setResponseText(value) { this.responseText = value; }
setResponseText(value: string) { this.responseText = value; }
setResponseURL(value) { this.responseURL = value; }
setResponseURL(value: string) { this.responseURL = value; }
setResponseHeaders(value) { this.responseHeaders = value; }
setResponseHeaders(value: string) { this.responseHeaders = value; }
getAllResponseHeaders() { return this.responseHeaders || ''; }
getResponseHeader(key) { return Headers.fromResponseHeaderString(this.responseHeaders).get(key); }
getResponseHeader(key: string) {
return Headers.fromResponseHeaderString(this.responseHeaders).get(key);
}
addEventListener(type: string, cb: Function) { this.callbacks.set(type, cb); }
@ -80,8 +82,8 @@ class MockBrowserXHR extends BrowserXhr {
export function main() {
describe('XHRBackend', () => {
var backend;
var sampleRequest;
var backend: XHRBackend;
var sampleRequest: Request;
beforeEach(() => {
var injector = Injector.resolveAndCreate([
@ -102,10 +104,10 @@ export function main() {
describe('XHRConnection', () => {
it('should use the injected BaseResponseOptions to create the response',
inject([AsyncTestCompleter], async => {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(),
new ResponseOptions({type: ResponseType.Error}));
connection.response.subscribe(res => {
connection.response.subscribe((res: Response) => {
expect(res.type).toBe(ResponseType.Error);
async.done();
});
@ -113,11 +115,12 @@ export function main() {
existingXHRs[0].dispatchEvent('load');
}));
it('should complete a request', inject([AsyncTestCompleter], async => {
it('should complete a request', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(),
new ResponseOptions({type: ResponseType.Error}));
connection.response.subscribe(res => { expect(res.type).toBe(ResponseType.Error); },
null, () => { async.done(); });
connection.response.subscribe((res: Response) => {
expect(res.type).toBe(ResponseType.Error);
}, null, () => { async.done(); });
existingXHRs[0].setStatusCode(200);
existingXHRs[0].dispatchEvent('load');
}));
@ -129,10 +132,11 @@ export function main() {
expect(abortSpy).toHaveBeenCalled();
});
it('should create an error Response on error', inject([AsyncTestCompleter], async => {
it('should create an error Response on error',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(),
new ResponseOptions({type: ResponseType.Error}));
connection.response.subscribe(null, res => {
connection.response.subscribe(null, (res: Response) => {
expect(res.type).toBe(ResponseType.Error);
async.done();
});
@ -170,13 +174,14 @@ export function main() {
expect(setRequestHeaderSpy).toHaveBeenCalledWith('X-Multi', 'a,b');
});
it('should return the correct status code', inject([AsyncTestCompleter], async => {
it('should return the correct status code',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var statusCode = 418;
var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(),
new ResponseOptions({status: statusCode}));
connection.response.subscribe(
res => {
(res: Response) => {
},
errRes => {
@ -188,7 +193,8 @@ export function main() {
existingXHRs[0].dispatchEvent('load');
}));
it('should call next and complete on 200 codes', inject([AsyncTestCompleter], async => {
it('should call next and complete on 200 codes',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var nextCalled = false;
var errorCalled = false;
var statusCode = 200;
@ -196,7 +202,7 @@ export function main() {
new ResponseOptions({status: statusCode}));
connection.response.subscribe(
res => {
(res: Response) => {
nextCalled = true;
expect(res.status).toBe(statusCode);
},
@ -210,14 +216,15 @@ export function main() {
existingXHRs[0].dispatchEvent('load');
}));
it('should call error and not complete on 300+ codes', inject([AsyncTestCompleter], async => {
it('should call error and not complete on 300+ codes',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var nextCalled = false;
var errorCalled = false;
var statusCode = 301;
var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(),
new ResponseOptions({status: statusCode}));
connection.response.subscribe(res => { nextCalled = true; }, errRes => {
connection.response.subscribe((res: Response) => { nextCalled = true; }, errRes => {
expect(errRes.status).toBe(statusCode);
expect(nextCalled).toBe(false);
async.done();
@ -226,13 +233,14 @@ export function main() {
existingXHRs[0].setStatusCode(statusCode);
existingXHRs[0].dispatchEvent('load');
}));
it('should normalize IE\'s 1223 status code into 204', inject([AsyncTestCompleter], async => {
it('should normalize IE\'s 1223 status code into 204',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var statusCode = 1223;
var normalizedCode = 204;
var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(),
new ResponseOptions({status: statusCode}));
connection.response.subscribe(res => {
connection.response.subscribe((res: Response) => {
expect(res.status).toBe(normalizedCode);
async.done();
});
@ -241,7 +249,8 @@ export function main() {
existingXHRs[0].dispatchEvent('load');
}));
it('should normalize responseText and response', inject([AsyncTestCompleter], async => {
it('should normalize responseText and response',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var responseBody = 'Doge';
var connection1 =
@ -250,7 +259,7 @@ export function main() {
var connection2 =
new XHRConnection(sampleRequest, new MockBrowserXHR(), new ResponseOptions());
connection1.response.subscribe(res => {
connection1.response.subscribe((res: Response) => {
expect(res.text()).toBe(responseBody);
connection2.response.subscribe(ress => {
@ -267,7 +276,7 @@ export function main() {
}));
it('should parse response headers and add them to the response',
inject([AsyncTestCompleter], async => {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var statusCode = 200;
var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(),
new ResponseOptions({status: statusCode}));
@ -278,7 +287,7 @@ export function main() {
Transfer-Encoding: chunked
Connection: keep-alive`
connection.response.subscribe(res => {
connection.response.subscribe((res: Response) => {
expect(res.headers.get('Date')).toEqual('Fri, 20 Nov 2015 01:45:26 GMT');
expect(res.headers.get('Content-Type')).toEqual('application/json; charset=utf-8');
expect(res.headers.get('Transfer-Encoding')).toEqual('chunked');
@ -291,12 +300,13 @@ export function main() {
existingXHRs[0].dispatchEvent('load');
}));
it('should add the responseURL to the response', inject([AsyncTestCompleter], async => {
it('should add the responseURL to the response',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var statusCode = 200;
var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(),
new ResponseOptions({status: statusCode}));
connection.response.subscribe(res => {
connection.response.subscribe((res: Response) => {
expect(res.url).toEqual('http://google.com');
async.done();
});
@ -307,14 +317,14 @@ export function main() {
}));
it('should add use the X-Request-URL in CORS situations',
inject([AsyncTestCompleter], async => {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var statusCode = 200;
var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(),
new ResponseOptions({status: statusCode}));
var responseHeaders = `X-Request-URL: http://somedomain.com
Foo: Bar`
connection.response.subscribe(res => {
connection.response.subscribe((res: Response) => {
expect(res.url).toEqual('http://somedomain.com');
async.done();
});

View File

@ -42,7 +42,7 @@ export function main() {
var jsonp: Jsonp;
it('should allow using jsonpInjectables and httpInjectables in same injector',
inject([AsyncTestCompleter], (async) => {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
parentInjector = Injector.resolveAndCreate([
provide(XHRBackend, {useClass: MockBackend}),
provide(JSONPBackend, {useClass: MockBackend})
@ -91,7 +91,7 @@ export function main() {
var http: Http;
var injector: Injector;
var backend: MockBackend;
var baseResponse;
var baseResponse: Response;
var jsonp: Jsonp;
beforeEach(() => {
injector = Injector.resolveAndCreate([
@ -129,19 +129,19 @@ export function main() {
it('should accept a fully-qualified request as its only parameter',
inject([AsyncTestCompleter], (async) => {
backend.connections.subscribe(c => {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.url).toBe('https://google.com');
c.mockRespond(new Response(new ResponseOptions({body: 'Thank you'})));
async.done();
});
http.request(new Request(new RequestOptions({url: 'https://google.com'})))
.subscribe((res) => {});
.subscribe((res: Response) => {});
}));
it('should accept a fully-qualified request as its only parameter',
inject([AsyncTestCompleter], (async) => {
backend.connections.subscribe(c => {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.url).toBe('https://google.com');
expect(c.request.method).toBe(RequestMethod.Post);
c.mockRespond(new Response(new ResponseOptions({body: 'Thank you'})));
@ -149,64 +149,64 @@ export function main() {
});
http.request(new Request(new RequestOptions(
{url: 'https://google.com', method: RequestMethod.Post})))
.subscribe((res) => {});
.subscribe((res: Response) => {});
}));
it('should perform a get request for given url if only passed a string',
inject([AsyncTestCompleter], (async) => {
backend.connections.subscribe(c => c.mockRespond(baseResponse));
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
backend.connections.subscribe((c: MockConnection) => c.mockRespond(baseResponse));
http.request('http://basic.connection')
.subscribe(res => {
.subscribe((res: Response) => {
expect(res.text()).toBe('base response');
async.done();
});
}));
it('should perform a post request for given url if options include a method',
inject([AsyncTestCompleter], (async) => {
backend.connections.subscribe(c => {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.method).toEqual(RequestMethod.Post);
c.mockRespond(baseResponse);
});
let requestOptions = new RequestOptions({method: RequestMethod.Post});
http.request('http://basic.connection', requestOptions)
.subscribe(res => {
.subscribe((res: Response) => {
expect(res.text()).toBe('base response');
async.done();
});
}));
it('should perform a post request for given url if options include a method',
inject([AsyncTestCompleter], (async) => {
backend.connections.subscribe(c => {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.method).toEqual(RequestMethod.Post);
c.mockRespond(baseResponse);
});
let requestOptions = {method: RequestMethod.Post};
http.request('http://basic.connection', requestOptions)
.subscribe(res => {
.subscribe((res: Response) => {
expect(res.text()).toBe('base response');
async.done();
});
}));
it('should perform a get request and complete the response',
inject([AsyncTestCompleter], (async) => {
backend.connections.subscribe(c => c.mockRespond(baseResponse));
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
backend.connections.subscribe((c: MockConnection) => c.mockRespond(baseResponse));
http.request('http://basic.connection')
.subscribe(res => { expect(res.text()).toBe('base response'); }, null,
.subscribe((res: Response) => { expect(res.text()).toBe('base response'); }, null,
() => { async.done(); });
}));
it('should perform multiple get requests and complete the responses',
inject([AsyncTestCompleter], (async) => {
backend.connections.subscribe(c => c.mockRespond(baseResponse));
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
backend.connections.subscribe((c: MockConnection) => c.mockRespond(baseResponse));
http.request('http://basic.connection')
.subscribe(res => { expect(res.text()).toBe('base response'); });
.subscribe((res: Response) => { expect(res.text()).toBe('base response'); });
http.request('http://basic.connection')
.subscribe(res => { expect(res.text()).toBe('base response'); }, null,
.subscribe((res: Response) => { expect(res.text()).toBe('base response'); }, null,
() => { async.done(); });
}));
@ -219,149 +219,160 @@ export function main() {
describe('.get()', () => {
it('should perform a get request for given url', inject([AsyncTestCompleter], async => {
backend.connections.subscribe(c => {
it('should perform a get request for given url',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.method).toBe(RequestMethod.Get);
backend.resolveAllConnections();
async.done();
});
http.get(url).subscribe(res => {});
http.get(url).subscribe((res: Response) => {});
}));
});
describe('.post()', () => {
it('should perform a post request for given url', inject([AsyncTestCompleter], async => {
backend.connections.subscribe(c => {
it('should perform a post request for given url',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.method).toBe(RequestMethod.Post);
backend.resolveAllConnections();
async.done();
});
http.post(url, 'post me').subscribe(res => {});
http.post(url, 'post me').subscribe((res: Response) => {});
}));
it('should attach the provided body to the request', inject([AsyncTestCompleter], async => {
it('should attach the provided body to the request',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var body = 'this is my post body';
backend.connections.subscribe(c => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.text()).toBe(body);
backend.resolveAllConnections();
async.done();
});
http.post(url, body).subscribe(res => {});
http.post(url, body).subscribe((res: Response) => {});
}));
});
describe('.put()', () => {
it('should perform a put request for given url', inject([AsyncTestCompleter], async => {
backend.connections.subscribe(c => {
it('should perform a put request for given url',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.method).toBe(RequestMethod.Put);
backend.resolveAllConnections();
async.done();
});
http.put(url, 'put me').subscribe(res => {});
http.put(url, 'put me').subscribe((res: Response) => {});
}));
it('should attach the provided body to the request', inject([AsyncTestCompleter], async => {
it('should attach the provided body to the request',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var body = 'this is my put body';
backend.connections.subscribe(c => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.text()).toBe(body);
backend.resolveAllConnections();
async.done();
});
http.put(url, body).subscribe(res => {});
http.put(url, body).subscribe((res: Response) => {});
}));
});
describe('.delete()', () => {
it('should perform a delete request for given url', inject([AsyncTestCompleter], async => {
backend.connections.subscribe(c => {
it('should perform a delete request for given url',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.method).toBe(RequestMethod.Delete);
backend.resolveAllConnections();
async.done();
});
http.delete(url).subscribe(res => {});
http.delete(url).subscribe((res: Response) => {});
}));
});
describe('.patch()', () => {
it('should perform a patch request for given url', inject([AsyncTestCompleter], async => {
backend.connections.subscribe(c => {
it('should perform a patch request for given url',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.method).toBe(RequestMethod.Patch);
backend.resolveAllConnections();
async.done();
});
http.patch(url, 'this is my patch body').subscribe(res => {});
http.patch(url, 'this is my patch body').subscribe((res: Response) => {});
}));
it('should attach the provided body to the request', inject([AsyncTestCompleter], async => {
it('should attach the provided body to the request',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var body = 'this is my patch body';
backend.connections.subscribe(c => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.text()).toBe(body);
backend.resolveAllConnections();
async.done();
});
http.patch(url, body).subscribe(res => {});
http.patch(url, body).subscribe((res: Response) => {});
}));
});
describe('.head()', () => {
it('should perform a head request for given url', inject([AsyncTestCompleter], async => {
backend.connections.subscribe(c => {
it('should perform a head request for given url',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.method).toBe(RequestMethod.Head);
backend.resolveAllConnections();
async.done();
});
http.head(url).subscribe(res => {});
http.head(url).subscribe((res: Response) => {});
}));
});
describe('searchParams', () => {
it('should append search params to url', inject([AsyncTestCompleter], async => {
it('should append search params to url',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var params = new URLSearchParams();
params.append('q', 'puppies');
backend.connections.subscribe(c => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.url).toEqual('https://www.google.com?q=puppies');
backend.resolveAllConnections();
async.done();
});
http.get('https://www.google.com', new RequestOptions({search: params}))
.subscribe(res => {});
.subscribe((res: Response) => {});
}));
it('should append string search params to url', inject([AsyncTestCompleter], async => {
backend.connections.subscribe(c => {
it('should append string search params to url',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.url).toEqual('https://www.google.com?q=piggies');
backend.resolveAllConnections();
async.done();
});
http.get('https://www.google.com', new RequestOptions({search: 'q=piggies'}))
.subscribe(res => {});
.subscribe((res: Response) => {});
}));
it('should produce valid url when url already contains a query',
inject([AsyncTestCompleter], async => {
backend.connections.subscribe(c => {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.url).toEqual('https://www.google.com?q=angular&as_eq=1.x');
backend.resolveAllConnections();
async.done();
});
http.get('https://www.google.com?q=angular', new RequestOptions({search: 'as_eq=1.x'}))
.subscribe(res => {});
.subscribe((res: Response) => {});
}));
});
describe('string method names', () => {
it('should allow case insensitive strings for method names', () => {
inject([AsyncTestCompleter], (async) => {
backend.connections.subscribe(c => {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.method)
.toBe(RequestMethod.Post)
c.mockRespond(new Response(new ResponseOptions({body: 'Thank you'})));
@ -369,7 +380,7 @@ export function main() {
});
http.request(
new Request(new RequestOptions({url: 'https://google.com', method: 'PosT'})))
.subscribe((res) => {});
.subscribe((res: Response) => {});
});
});