angular-cn/modules/@angular/common/testing/location_mock.ts

82 lines
2.2 KiB
TypeScript
Raw Normal View History

import {Injectable, EventEmitter} from '@angular/core';
import {ObservableWrapper} from '../src/facade/async';
import {Location} from '../index';
2015-04-21 14:23:23 -04:00
/**
* A spy for {@link Location} that allows tests to fire simulated location events.
*/
@Injectable()
2015-08-26 14:41:41 -04:00
export class SpyLocation implements Location {
urlChanges: string[] = [];
/** @internal */
2015-08-26 14:41:41 -04:00
_path: string = '';
/** @internal */
_query: string = '';
/** @internal */
_subject: EventEmitter<any> = new EventEmitter();
/** @internal */
2015-08-26 14:41:41 -04:00
_baseHref: string = '';
2015-04-21 14:23:23 -04:00
setInitialPath(url: string) { this._path = url; }
2015-04-21 14:23:23 -04:00
setBaseHref(url: string) { this._baseHref = url; }
path(): string { return this._path; }
2015-04-21 14:23:23 -04:00
simulateUrlPop(pathname: string) {
ObservableWrapper.callEmit(this._subject, {'url': pathname, 'pop': true});
}
simulateHashChange(pathname: string) {
// Because we don't prevent the native event, the browser will independently update the path
this.setInitialPath(pathname);
this.urlChanges.push('hash: ' + pathname);
ObservableWrapper.callEmit(this._subject, {'url': pathname, 'pop': true, 'type': 'hashchange'});
}
2015-04-21 14:23:23 -04:00
prepareExternalUrl(url: string): string {
if (url.length > 0 && !url.startsWith('/')) {
url = '/' + url;
}
return this._baseHref + url;
}
go(path: string, query: string = '') {
path = this.prepareExternalUrl(path);
if (this._path == path && this._query == query) {
2015-04-21 14:23:23 -04:00
return;
}
this._path = path;
this._query = query;
var url = path + (query.length > 0 ? ('?' + query) : '');
this.urlChanges.push(url);
2015-04-21 14:23:23 -04:00
}
replaceState(path: string, query: string = '') {
path = this.prepareExternalUrl(path);
this._path = path;
this._query = query;
var url = path + (query.length > 0 ? ('?' + query) : '');
this.urlChanges.push('replace: ' + url);
}
2015-04-21 14:23:23 -04:00
forward() {
// TODO
}
back() {
// TODO
}
subscribe(onNext: (value: any) => void, onThrow: (error: any) => void = null,
onReturn: () => void = null): Object {
return ObservableWrapper.subscribe(this._subject, onNext, onThrow, onReturn);
2015-04-21 14:23:23 -04:00
}
2015-08-26 14:41:41 -04:00
// TODO: remove these once Location is an interface, and can be implemented cleanly
platformStrategy: any = null;
normalize(url: string): string { return null; }
2015-04-21 14:23:23 -04:00
}