testing.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. /**
  2. * @license Angular v8.1.0
  3. * (c) 2010-2019 Google LLC. https://angular.io/
  4. * License: MIT
  5. */
  6. import { __decorate, __extends, __metadata, __assign, __param } from 'tslib';
  7. import { Injectable, EventEmitter, InjectionToken, Inject, Optional } from '@angular/core';
  8. import { LocationStrategy } from '@angular/common';
  9. import { Subject } from 'rxjs';
  10. /**
  11. * @license
  12. * Copyright Google Inc. All Rights Reserved.
  13. *
  14. * Use of this source code is governed by an MIT-style license that can be
  15. * found in the LICENSE file at https://angular.io/license
  16. */
  17. /**
  18. * A spy for {@link Location} that allows tests to fire simulated location events.
  19. *
  20. * @publicApi
  21. */
  22. var SpyLocation = /** @class */ (function () {
  23. function SpyLocation() {
  24. this.urlChanges = [];
  25. this._history = [new LocationState('', '', null)];
  26. this._historyIndex = 0;
  27. /** @internal */
  28. this._subject = new EventEmitter();
  29. /** @internal */
  30. this._baseHref = '';
  31. /** @internal */
  32. this._platformStrategy = null;
  33. /** @internal */
  34. this._platformLocation = null;
  35. /** @internal */
  36. this._urlChangeListeners = [];
  37. }
  38. SpyLocation.prototype.setInitialPath = function (url) { this._history[this._historyIndex].path = url; };
  39. SpyLocation.prototype.setBaseHref = function (url) { this._baseHref = url; };
  40. SpyLocation.prototype.path = function () { return this._history[this._historyIndex].path; };
  41. SpyLocation.prototype.getState = function () { return this._history[this._historyIndex].state; };
  42. SpyLocation.prototype.isCurrentPathEqualTo = function (path, query) {
  43. if (query === void 0) { query = ''; }
  44. var givenPath = path.endsWith('/') ? path.substring(0, path.length - 1) : path;
  45. var currPath = this.path().endsWith('/') ? this.path().substring(0, this.path().length - 1) : this.path();
  46. return currPath == givenPath + (query.length > 0 ? ('?' + query) : '');
  47. };
  48. SpyLocation.prototype.simulateUrlPop = function (pathname) {
  49. this._subject.emit({ 'url': pathname, 'pop': true, 'type': 'popstate' });
  50. };
  51. SpyLocation.prototype.simulateHashChange = function (pathname) {
  52. // Because we don't prevent the native event, the browser will independently update the path
  53. this.setInitialPath(pathname);
  54. this.urlChanges.push('hash: ' + pathname);
  55. this._subject.emit({ 'url': pathname, 'pop': true, 'type': 'hashchange' });
  56. };
  57. SpyLocation.prototype.prepareExternalUrl = function (url) {
  58. if (url.length > 0 && !url.startsWith('/')) {
  59. url = '/' + url;
  60. }
  61. return this._baseHref + url;
  62. };
  63. SpyLocation.prototype.go = function (path, query, state) {
  64. if (query === void 0) { query = ''; }
  65. if (state === void 0) { state = null; }
  66. path = this.prepareExternalUrl(path);
  67. if (this._historyIndex > 0) {
  68. this._history.splice(this._historyIndex + 1);
  69. }
  70. this._history.push(new LocationState(path, query, state));
  71. this._historyIndex = this._history.length - 1;
  72. var locationState = this._history[this._historyIndex - 1];
  73. if (locationState.path == path && locationState.query == query) {
  74. return;
  75. }
  76. var url = path + (query.length > 0 ? ('?' + query) : '');
  77. this.urlChanges.push(url);
  78. this._subject.emit({ 'url': url, 'pop': false });
  79. };
  80. SpyLocation.prototype.replaceState = function (path, query, state) {
  81. if (query === void 0) { query = ''; }
  82. if (state === void 0) { state = null; }
  83. path = this.prepareExternalUrl(path);
  84. var history = this._history[this._historyIndex];
  85. if (history.path == path && history.query == query) {
  86. return;
  87. }
  88. history.path = path;
  89. history.query = query;
  90. history.state = state;
  91. var url = path + (query.length > 0 ? ('?' + query) : '');
  92. this.urlChanges.push('replace: ' + url);
  93. };
  94. SpyLocation.prototype.forward = function () {
  95. if (this._historyIndex < (this._history.length - 1)) {
  96. this._historyIndex++;
  97. this._subject.emit({ 'url': this.path(), 'state': this.getState(), 'pop': true });
  98. }
  99. };
  100. SpyLocation.prototype.back = function () {
  101. if (this._historyIndex > 0) {
  102. this._historyIndex--;
  103. this._subject.emit({ 'url': this.path(), 'state': this.getState(), 'pop': true });
  104. }
  105. };
  106. SpyLocation.prototype.onUrlChange = function (fn) {
  107. var _this = this;
  108. this._urlChangeListeners.push(fn);
  109. this.subscribe(function (v) { _this._notifyUrlChangeListeners(v.url, v.state); });
  110. };
  111. /** @internal */
  112. SpyLocation.prototype._notifyUrlChangeListeners = function (url, state) {
  113. if (url === void 0) { url = ''; }
  114. this._urlChangeListeners.forEach(function (fn) { return fn(url, state); });
  115. };
  116. SpyLocation.prototype.subscribe = function (onNext, onThrow, onReturn) {
  117. return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn });
  118. };
  119. SpyLocation.prototype.normalize = function (url) { return null; };
  120. SpyLocation = __decorate([
  121. Injectable()
  122. ], SpyLocation);
  123. return SpyLocation;
  124. }());
  125. var LocationState = /** @class */ (function () {
  126. function LocationState(path, query, state) {
  127. this.path = path;
  128. this.query = query;
  129. this.state = state;
  130. }
  131. return LocationState;
  132. }());
  133. /**
  134. * @license
  135. * Copyright Google Inc. All Rights Reserved.
  136. *
  137. * Use of this source code is governed by an MIT-style license that can be
  138. * found in the LICENSE file at https://angular.io/license
  139. */
  140. /**
  141. * A mock implementation of {@link LocationStrategy} that allows tests to fire simulated
  142. * location events.
  143. *
  144. * @publicApi
  145. */
  146. var MockLocationStrategy = /** @class */ (function (_super) {
  147. __extends(MockLocationStrategy, _super);
  148. function MockLocationStrategy() {
  149. var _this = _super.call(this) || this;
  150. _this.internalBaseHref = '/';
  151. _this.internalPath = '/';
  152. _this.internalTitle = '';
  153. _this.urlChanges = [];
  154. /** @internal */
  155. _this._subject = new EventEmitter();
  156. _this.stateChanges = [];
  157. return _this;
  158. }
  159. MockLocationStrategy.prototype.simulatePopState = function (url) {
  160. this.internalPath = url;
  161. this._subject.emit(new _MockPopStateEvent(this.path()));
  162. };
  163. MockLocationStrategy.prototype.path = function (includeHash) {
  164. if (includeHash === void 0) { includeHash = false; }
  165. return this.internalPath;
  166. };
  167. MockLocationStrategy.prototype.prepareExternalUrl = function (internal) {
  168. if (internal.startsWith('/') && this.internalBaseHref.endsWith('/')) {
  169. return this.internalBaseHref + internal.substring(1);
  170. }
  171. return this.internalBaseHref + internal;
  172. };
  173. MockLocationStrategy.prototype.pushState = function (ctx, title, path, query) {
  174. // Add state change to changes array
  175. this.stateChanges.push(ctx);
  176. this.internalTitle = title;
  177. var url = path + (query.length > 0 ? ('?' + query) : '');
  178. this.internalPath = url;
  179. var externalUrl = this.prepareExternalUrl(url);
  180. this.urlChanges.push(externalUrl);
  181. };
  182. MockLocationStrategy.prototype.replaceState = function (ctx, title, path, query) {
  183. // Reset the last index of stateChanges to the ctx (state) object
  184. this.stateChanges[(this.stateChanges.length || 1) - 1] = ctx;
  185. this.internalTitle = title;
  186. var url = path + (query.length > 0 ? ('?' + query) : '');
  187. this.internalPath = url;
  188. var externalUrl = this.prepareExternalUrl(url);
  189. this.urlChanges.push('replace: ' + externalUrl);
  190. };
  191. MockLocationStrategy.prototype.onPopState = function (fn) { this._subject.subscribe({ next: fn }); };
  192. MockLocationStrategy.prototype.getBaseHref = function () { return this.internalBaseHref; };
  193. MockLocationStrategy.prototype.back = function () {
  194. if (this.urlChanges.length > 0) {
  195. this.urlChanges.pop();
  196. this.stateChanges.pop();
  197. var nextUrl = this.urlChanges.length > 0 ? this.urlChanges[this.urlChanges.length - 1] : '';
  198. this.simulatePopState(nextUrl);
  199. }
  200. };
  201. MockLocationStrategy.prototype.forward = function () { throw 'not implemented'; };
  202. MockLocationStrategy.prototype.getState = function () { return this.stateChanges[(this.stateChanges.length || 1) - 1]; };
  203. MockLocationStrategy = __decorate([
  204. Injectable(),
  205. __metadata("design:paramtypes", [])
  206. ], MockLocationStrategy);
  207. return MockLocationStrategy;
  208. }(LocationStrategy));
  209. var _MockPopStateEvent = /** @class */ (function () {
  210. function _MockPopStateEvent(newUrl) {
  211. this.newUrl = newUrl;
  212. this.pop = true;
  213. this.type = 'popstate';
  214. }
  215. return _MockPopStateEvent;
  216. }());
  217. /**
  218. * @license
  219. * Copyright Google Inc. All Rights Reserved.
  220. *
  221. * Use of this source code is governed by an MIT-style license that can be
  222. * found in the LICENSE file at https://angular.io/license
  223. */
  224. /**
  225. * Parser from https://tools.ietf.org/html/rfc3986#appendix-B
  226. * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
  227. * 12 3 4 5 6 7 8 9
  228. *
  229. * Example: http://www.ics.uci.edu/pub/ietf/uri/#Related
  230. *
  231. * Results in:
  232. *
  233. * $1 = http:
  234. * $2 = http
  235. * $3 = //www.ics.uci.edu
  236. * $4 = www.ics.uci.edu
  237. * $5 = /pub/ietf/uri/
  238. * $6 = <undefined>
  239. * $7 = <undefined>
  240. * $8 = #Related
  241. * $9 = Related
  242. */
  243. var urlParse = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
  244. function parseUrl(urlStr, baseHref) {
  245. var verifyProtocol = /^((http[s]?|ftp):\/\/)/;
  246. var serverBase;
  247. // URL class requires full URL. If the URL string doesn't start with protocol, we need to add
  248. // an arbitrary base URL which can be removed afterward.
  249. if (!verifyProtocol.test(urlStr)) {
  250. serverBase = 'http://empty.com/';
  251. }
  252. var parsedUrl;
  253. try {
  254. parsedUrl = new URL(urlStr, serverBase);
  255. }
  256. catch (e) {
  257. var result = urlParse.exec(serverBase || '' + urlStr);
  258. if (!result) {
  259. throw new Error("Invalid URL: " + urlStr + " with base: " + baseHref);
  260. }
  261. var hostSplit = result[4].split(':');
  262. parsedUrl = {
  263. protocol: result[1],
  264. hostname: hostSplit[0],
  265. port: hostSplit[1] || '',
  266. pathname: result[5],
  267. search: result[6],
  268. hash: result[8],
  269. };
  270. }
  271. if (parsedUrl.pathname && parsedUrl.pathname.indexOf(baseHref) === 0) {
  272. parsedUrl.pathname = parsedUrl.pathname.substring(baseHref.length);
  273. }
  274. return {
  275. hostname: !serverBase && parsedUrl.hostname || '',
  276. protocol: !serverBase && parsedUrl.protocol || '',
  277. port: !serverBase && parsedUrl.port || '',
  278. pathname: parsedUrl.pathname || '/',
  279. search: parsedUrl.search || '',
  280. hash: parsedUrl.hash || '',
  281. };
  282. }
  283. /**
  284. * Provider for mock platform location config
  285. *
  286. * @publicApi
  287. */
  288. var MOCK_PLATFORM_LOCATION_CONFIG = new InjectionToken('MOCK_PLATFORM_LOCATION_CONFIG');
  289. /**
  290. * Mock implementation of URL state.
  291. *
  292. * @publicApi
  293. */
  294. var MockPlatformLocation = /** @class */ (function () {
  295. function MockPlatformLocation(config) {
  296. this.baseHref = '';
  297. this.hashUpdate = new Subject();
  298. this.urlChanges = [{ hostname: '', protocol: '', port: '', pathname: '/', search: '', hash: '', state: null }];
  299. if (config) {
  300. this.baseHref = config.appBaseHref || '';
  301. var parsedChanges = this.parseChanges(null, config.startUrl || 'http://<empty>/', this.baseHref);
  302. this.urlChanges[0] = __assign({}, parsedChanges);
  303. }
  304. }
  305. Object.defineProperty(MockPlatformLocation.prototype, "hostname", {
  306. get: function () { return this.urlChanges[0].hostname; },
  307. enumerable: true,
  308. configurable: true
  309. });
  310. Object.defineProperty(MockPlatformLocation.prototype, "protocol", {
  311. get: function () { return this.urlChanges[0].protocol; },
  312. enumerable: true,
  313. configurable: true
  314. });
  315. Object.defineProperty(MockPlatformLocation.prototype, "port", {
  316. get: function () { return this.urlChanges[0].port; },
  317. enumerable: true,
  318. configurable: true
  319. });
  320. Object.defineProperty(MockPlatformLocation.prototype, "pathname", {
  321. get: function () { return this.urlChanges[0].pathname; },
  322. enumerable: true,
  323. configurable: true
  324. });
  325. Object.defineProperty(MockPlatformLocation.prototype, "search", {
  326. get: function () { return this.urlChanges[0].search; },
  327. enumerable: true,
  328. configurable: true
  329. });
  330. Object.defineProperty(MockPlatformLocation.prototype, "hash", {
  331. get: function () { return this.urlChanges[0].hash; },
  332. enumerable: true,
  333. configurable: true
  334. });
  335. Object.defineProperty(MockPlatformLocation.prototype, "state", {
  336. get: function () { return this.urlChanges[0].state; },
  337. enumerable: true,
  338. configurable: true
  339. });
  340. MockPlatformLocation.prototype.getBaseHrefFromDOM = function () { return this.baseHref; };
  341. MockPlatformLocation.prototype.onPopState = function (fn) {
  342. // No-op: a state stack is not implemented, so
  343. // no events will ever come.
  344. };
  345. MockPlatformLocation.prototype.onHashChange = function (fn) { this.hashUpdate.subscribe(fn); };
  346. Object.defineProperty(MockPlatformLocation.prototype, "href", {
  347. get: function () {
  348. var url = this.protocol + "//" + this.hostname + (this.port ? ':' + this.port : '');
  349. url += "" + (this.pathname === '/' ? '' : this.pathname) + this.search + this.hash;
  350. return url;
  351. },
  352. enumerable: true,
  353. configurable: true
  354. });
  355. Object.defineProperty(MockPlatformLocation.prototype, "url", {
  356. get: function () { return "" + this.pathname + this.search + this.hash; },
  357. enumerable: true,
  358. configurable: true
  359. });
  360. MockPlatformLocation.prototype.parseChanges = function (state, url, baseHref) {
  361. if (baseHref === void 0) { baseHref = ''; }
  362. // When the `history.state` value is stored, it is always copied.
  363. state = JSON.parse(JSON.stringify(state));
  364. return __assign({}, parseUrl(url, baseHref), { state: state });
  365. };
  366. MockPlatformLocation.prototype.replaceState = function (state, title, newUrl) {
  367. var _a = this.parseChanges(state, newUrl), pathname = _a.pathname, search = _a.search, parsedState = _a.state, hash = _a.hash;
  368. this.urlChanges[0] = __assign({}, this.urlChanges[0], { pathname: pathname, search: search, hash: hash, state: parsedState });
  369. };
  370. MockPlatformLocation.prototype.pushState = function (state, title, newUrl) {
  371. var _a = this.parseChanges(state, newUrl), pathname = _a.pathname, search = _a.search, parsedState = _a.state, hash = _a.hash;
  372. this.urlChanges.unshift(__assign({}, this.urlChanges[0], { pathname: pathname, search: search, hash: hash, state: parsedState }));
  373. };
  374. MockPlatformLocation.prototype.forward = function () { throw new Error('Not implemented'); };
  375. MockPlatformLocation.prototype.back = function () {
  376. var _this = this;
  377. var oldUrl = this.url;
  378. var oldHash = this.hash;
  379. this.urlChanges.shift();
  380. var newHash = this.hash;
  381. if (oldHash !== newHash) {
  382. scheduleMicroTask(function () { return _this.hashUpdate.next({
  383. type: 'hashchange', state: null, oldUrl: oldUrl, newUrl: _this.url
  384. }); });
  385. }
  386. };
  387. MockPlatformLocation.prototype.getState = function () { return this.state; };
  388. MockPlatformLocation = __decorate([
  389. Injectable(),
  390. __param(0, Inject(MOCK_PLATFORM_LOCATION_CONFIG)), __param(0, Optional()),
  391. __metadata("design:paramtypes", [Object])
  392. ], MockPlatformLocation);
  393. return MockPlatformLocation;
  394. }());
  395. function scheduleMicroTask(cb) {
  396. Promise.resolve(null).then(cb);
  397. }
  398. /**
  399. * @license
  400. * Copyright Google Inc. All Rights Reserved.
  401. *
  402. * Use of this source code is governed by an MIT-style license that can be
  403. * found in the LICENSE file at https://angular.io/license
  404. */
  405. /**
  406. * @license
  407. * Copyright Google Inc. All Rights Reserved.
  408. *
  409. * Use of this source code is governed by an MIT-style license that can be
  410. * found in the LICENSE file at https://angular.io/license
  411. */
  412. // This file only reexports content of the `src` folder. Keep it that way.
  413. /**
  414. * @license
  415. * Copyright Google Inc. All Rights Reserved.
  416. *
  417. * Use of this source code is governed by an MIT-style license that can be
  418. * found in the LICENSE file at https://angular.io/license
  419. */
  420. /**
  421. * Generated bundle index. Do not edit.
  422. */
  423. export { SpyLocation, MockLocationStrategy, MOCK_PLATFORM_LOCATION_CONFIG, MockPlatformLocation };
  424. //# sourceMappingURL=testing.js.map