Modular logistics and supply chain operating system (LSOS)
JavaScript driver-appfleet-managementfreight-managementinfrastructureinventory-managementlast-mile-deliverylogisticsondemandopen-sourceorder-managementroute-optimizationsupply-chain-managementtracking-and-monitoringtransport-management-systemtransportationwarehouse-management
test(console): cover the runtime-config and router-refresh-patch utils
Ronald A. Richardsonfe316fa26937
diff --git a/console/tests/unit/utils/router-refresh-patch-test.js b/console/tests/unit/utils/router-refresh-patch-test.jsindex e483626d..c6b213f8 100644--- a/console/tests/unit/utils/router-refresh-patch-test.js+++ b/console/tests/unit/utils/router-refresh-patch-test.js@@ -1,45 +1,224 @@+// This util patches Ember's private router microlib, so the tests necessarily reach for+// the same private API the patch itself targets.+/* eslint-disable ember/no-private-routing-service */import applyRouterFix, { patchRouterRefresh, suppressRouterRefreshErrors } from '@fleetbase/console/utils/router-refresh-patch';import { module, test } from 'qunit';+const STATE_SYMBOL = 'state-symbol';++// Stands in for Ember's RouterMicrolib. `this.constructor` inside the patched refresh must+// carry STATE_SYMBOL and NamedTransitionIntent, so the fake has to be a real class.+class FakeMicrolib {+ static STATE_SYMBOL = STATE_SYMBOL;+ static NamedTransitionIntent = class {+ constructor(router, name, pivotRoute, contexts, queryParams) {+ Object.assign(this, { router, name, pivotRoute, contexts, queryParams });+ }+ };++ constructor({ routeInfos, queryParams = {}, handlers = [], activeTransition = null, changedQueryParams = null } = {}) {+ this.state = { routeInfos, queryParams };+ this.activeTransition = activeTransition;+ this._changedQueryParams = changedQueryParams;+ this.recognizer = { handlersFor: () => handlers };+ this.intents = [];+ this.methodCalls = [];+ }++ refresh() {+ return 'original';+ }++ transitionByIntent(intent, isIntermediate) {+ this.intents.push({ intent, isIntermediate });+ return { method: (m) => this.methodCalls.push(m) };+ }+}++function patch(microlib) {+ patchRouterRefresh({ lookup: () => ({ _routerMicrolib: microlib }) });+ return microlib;+}+module('Unit | Utility | router-refresh-patch', function () {- test('patchRouterRefresh ignores invalid application instances', function (assert) {- assert.strictEqual(patchRouterRefresh(null), undefined);- assert.strictEqual(patchRouterRefresh({}), undefined, 'no lookup() => no-op');- assert.ok(true, 'did not throw');+ test('patchRouterRefresh ignores an application it cannot use', function (assert) {+ assert.strictEqual(patchRouterRefresh(null), undefined, 'no application');+ assert.strictEqual(patchRouterRefresh({}), undefined, 'an application with no lookup()');+ assert.strictEqual(patchRouterRefresh({ lookup: () => null }), undefined, 'no router');+ assert.strictEqual(patchRouterRefresh({ lookup: () => ({}) }), undefined, 'a router with no microlib');});- test('patchRouterRefresh does nothing when the router has no microlib', function (assert) {- const app = { lookup: () => ({}) };- patchRouterRefresh(app);- assert.ok(true, 'did not throw');+ test('patchRouterRefresh wraps refresh once and marks it patched', function (assert) {+ const microlib = new FakeMicrolib({ routeInfos: [{ route: 'r', name: 'n' }] });+ const original = microlib.refresh;++ patch(microlib);+ assert.true(microlib._fleetbaseRefreshPatched, 'the microlib is marked');+ assert.notStrictEqual(microlib.refresh, original, 'refresh is wrapped');++ const wrapped = microlib.refresh;+ patch(microlib);+ assert.strictEqual(microlib.refresh, wrapped, 'a second application is a no-op');});- test('patchRouterRefresh wraps refresh once and marks it patched', function (assert) {- const originalRefresh = function () {- return 'orig';+ test('the patched refresh defaults the pivot route to the first route info', function (assert) {+ const microlib = patch(+ new FakeMicrolib({+ routeInfos: [{ route: 'first-route', name: 'first' }, { name: 'last' }],+ queryParams: { page: 2 },+ })+ );++ microlib.refresh();++ const { intent, isIntermediate } = microlib.intents.at(-1);+ assert.strictEqual(intent.pivotRoute, 'first-route', 'the pivot defaults to the first route');+ assert.strictEqual(intent.name, 'last', 'the intent targets the leaf route');+ assert.deepEqual(intent.queryParams, { page: 2 }, 'the state query params are carried over');+ assert.false(isIntermediate);+ });++ test('an explicit pivot route is respected', function (assert) {+ const microlib = patch(new FakeMicrolib({ routeInfos: [{ route: 'first', name: 'first' }, { name: 'last' }] }));++ microlib.refresh('explicit-pivot');++ assert.strictEqual(microlib.intents.at(-1).intent.pivotRoute, 'explicit-pivot');+ });++ test('dynamic segments are preserved as intent contexts', function (assert) {+ // This is the whole point of the patch: the stock refresh passes [] and loses the+ // dynamic segments, producing the "not enough parameters" error.+ const microlib = patch(+ new FakeMicrolib({+ routeInfos: [+ { route: 'first', name: 'first' },+ { name: 'orders.order', params: { order_id: 'ord_1', missing: undefined } },+ ],+ handlers: [{ names: [] }, { names: ['order_id', 'missing'] }],+ })+ );++ microlib.refresh();++ assert.deepEqual(microlib.intents.at(-1).intent.contexts, ['ord_1'], 'defined params become contexts, undefined ones are skipped');+ });++ test('a leaf route without params contributes no contexts', function (assert) {+ const microlib = patch(new FakeMicrolib({ routeInfos: [{ route: 'first', name: 'first' }, { name: 'index' }], handlers: [{ names: ['id'] }] }));++ microlib.refresh();++ assert.deepEqual(microlib.intents.at(-1).intent.contexts, []);+ });++ test('a handler with no names contributes no contexts', function (assert) {+ const microlib = patch(+ new FakeMicrolib({+ routeInfos: [+ { route: 'first', name: 'first' },+ { name: 'index', params: { id: '1' } },+ ],+ handlers: [{ names: [] }],+ })+ );++ microlib.refresh();++ assert.deepEqual(microlib.intents.at(-1).intent.contexts, []);+ });++ test('an in-flight transition supplies the state and its replace method is preserved', function (assert) {+ const activeTransition = {+ urlMethod: 'replace',+ [STATE_SYMBOL]: { routeInfos: [{ route: 'from-transition', name: 'first' }, { name: 'last' }], queryParams: { q: 1 } },};- const microlib = { refresh: originalRefresh };- const app = { lookup: (name) => (name === 'router:main' ? { _routerMicrolib: microlib } : null) };+ const microlib = patch(new FakeMicrolib({ routeInfos: [{ route: 'unused', name: 'unused' }], activeTransition }));- patchRouterRefresh(app);- assert.true(microlib._fleetbaseRefreshPatched, 'marked as patched');- assert.notStrictEqual(microlib.refresh, originalRefresh, 'refresh was wrapped');+ microlib.refresh();- const wrapped = microlib.refresh;- patchRouterRefresh(app);- assert.strictEqual(microlib.refresh, wrapped, 'second call is a no-op');+ assert.strictEqual(microlib.intents.at(-1).intent.pivotRoute, 'from-transition', 'the active transition state wins');+ assert.deepEqual(microlib.methodCalls, ['replace'], 'the replace url method carries over');+ });++ test('a non-replace transition does not set a url method', function (assert) {+ const activeTransition = {+ urlMethod: 'update',+ [STATE_SYMBOL]: { routeInfos: [{ route: 'r', name: 'first' }, { name: 'last' }], queryParams: {} },+ };+ const microlib = patch(new FakeMicrolib({ routeInfos: [{ route: 'r', name: 'r' }], activeTransition }));++ microlib.refresh();++ assert.deepEqual(microlib.methodCalls, [], 'no method override');+ });++ test('changed query params take precedence over the state query params', function (assert) {+ const microlib = patch(+ new FakeMicrolib({+ routeInfos: [{ route: 'first', name: 'first' }, { name: 'last' }],+ queryParams: { page: 1 },+ changedQueryParams: { page: 9 },+ })+ );++ microlib.refresh();++ assert.deepEqual(microlib.intents.at(-1).intent.queryParams, { page: 9 });+ });++ test('a throwing lookup is swallowed so boot continues', function (assert) {+ assert.strictEqual(+ patchRouterRefresh({+ lookup() {+ throw new Error('router unavailable');+ },+ }),+ undefined,+ 'the error is caught'+ );});test('suppressRouterRefreshErrors ignores a missing application', function (assert) {assert.strictEqual(suppressRouterRefreshErrors(null), undefined);- assert.ok(true, 'did not throw');});- test('applyRouterFix applies the patch (without installing global error suppression)', function (assert) {- const microlib = { refresh() {} };- const app = { lookup: () => ({ _routerMicrolib: microlib }) };+ test('suppressRouterRefreshErrors swallows the known refresh error via Ember.onerror', function (assert) {+ const originalEmber = window.Ember;+ const seen = [];+ window.Ember = { onerror: (error) => seen.push(error) };++ try {+ suppressRouterRefreshErrors({});++ const known = new Error("You didn't provide enough string/numeric parameters to satisfy all of the dynamic segments");+ assert.strictEqual(window.Ember.onerror(known), undefined, 'the known error is suppressed');+ assert.deepEqual(seen, [], 'it never reaches the original handler');++ const other = new Error('something else');+ window.Ember.onerror(other);+ assert.deepEqual(seen, [other], 'unrelated errors pass through to the original handler');+ } finally {+ window.Ember = originalEmber;+ }+ });++ test('without an original handler an unrelated error is rethrown', function (assert) {+ const originalEmber = window.Ember;+ window.Ember = { onerror: null };++ try {+ suppressRouterRefreshErrors({});+ assert.throws(() => window.Ember.onerror(new Error('boom')), /boom/, 'unrelated errors still surface');+ } finally {+ window.Ember = originalEmber;+ }+ });++ test('applyRouterFix applies the patch and can skip error suppression', function (assert) {+ const microlib = new FakeMicrolib({ routeInfos: [{ route: 'r', name: 'r' }] });- applyRouterFix(app, { suppressErrors: false });+ applyRouterFix({ lookup: () => ({ _routerMicrolib: microlib }) }, { suppressErrors: false });assert.true(microlib._fleetbaseRefreshPatched);});diff --git a/console/tests/unit/utils/runtime-config-test.js b/console/tests/unit/utils/runtime-config-test.jsindex 781f7fed..8c76795a 100644--- a/console/tests/unit/utils/runtime-config-test.js+++ b/console/tests/unit/utils/runtime-config-test.js@@ -1,10 +1,86 @@-import runtimeConfig from '@fleetbase/console/utils/runtime-config';import { module, test } from 'qunit';+import { setupTest } from '@fleetbase/console/tests/helpers';+import { applyRuntimeConfig, clearRuntimeConfigCache } from '@fleetbase/console/utils/runtime-config';+import config from '@fleetbase/console/config/environment';+import { get, set } from '@ember/object';-module('Unit | Utility | runtime-config', function () {- // TODO: Replace this with your real tests.- test('it works', function (assert) {- let result = runtimeConfig();- assert.ok(result);+const TOUCHED_PATHS = ['API.host', 'API.namespace', 'socket.path', 'socket.hostname', 'socket.secure', 'socket.port', 'osrm.host', 'APP.extensions'];++module('Unit | Utility | runtime-config', function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ // applyRuntimeConfig writes straight into the shared environment config, so+ // snapshot everything it can touch and put it back afterwards.+ this.snapshot = TOUCHED_PATHS.map((path) => [path, get(config, path)]);+ });++ hooks.afterEach(function () {+ this.snapshot.forEach(([path, value]) => set(config, path, value));+ });++ test('it maps the runtime keys onto their config paths', function (assert) {+ applyRuntimeConfig({+ API_HOST: 'https://api.example.com',+ API_NAMESPACE: 'v2',+ SOCKETCLUSTER_HOST: 'socket.example.com',+ SOCKETCLUSTER_PATH: '/ws',+ OSRM_HOST: 'https://osrm.example.com',+ });++ assert.strictEqual(get(config, 'API.host'), 'https://api.example.com');+ assert.strictEqual(get(config, 'API.namespace'), 'v2');+ assert.strictEqual(get(config, 'socket.hostname'), 'socket.example.com');+ assert.strictEqual(get(config, 'socket.path'), '/ws');+ assert.strictEqual(get(config, 'osrm.host'), 'https://osrm.example.com');+ });++ test('the socket port is coerced to a number', function (assert) {+ applyRuntimeConfig({ SOCKETCLUSTER_PORT: '8000' });++ assert.strictEqual(get(config, 'socket.port'), 8000, 'a string port becomes an integer');+ });++ test('the secure flag is coerced to a boolean', function (assert) {+ applyRuntimeConfig({ SOCKETCLUSTER_SECURE: 'true' });+ assert.true(get(config, 'socket.secure'), 'the string "true" becomes true');++ applyRuntimeConfig({ SOCKETCLUSTER_SECURE: 'false' });+ assert.false(get(config, 'socket.secure'), 'the string "false" becomes false');+ });++ test('extensions are coerced to an array from either a string or a list', function (assert) {+ applyRuntimeConfig({ EXTENSIONS: 'fleet-ops,storefront,pallet' });+ assert.deepEqual(get(config, 'APP.extensions'), ['fleet-ops', 'storefront', 'pallet'], 'a comma separated string splits');++ applyRuntimeConfig({ EXTENSIONS: ['fleet-ops'] });+ assert.deepEqual(get(config, 'APP.extensions'), ['fleet-ops'], 'an existing array is copied');+ });++ test('unmapped keys are ignored rather than written', function (assert) {+ const before = get(config, 'API.host');++ applyRuntimeConfig({ NOT_A_REAL_KEY: 'whatever' });++ assert.strictEqual(get(config, 'API.host'), before, 'nothing else is disturbed');+ assert.strictEqual(config.NOT_A_REAL_KEY, undefined, 'the unknown key is not set anywhere');+ });++ test('an empty config is a no-op', function (assert) {+ const before = get(config, 'API.host');++ applyRuntimeConfig();++ assert.strictEqual(get(config, 'API.host'), before);+ });++ test('clearRuntimeConfigCache removes both cache entries', function (assert) {+ window.localStorage.setItem('fleetbase_runtime_config', JSON.stringify({ config: {}, timestamp: Date.now() }));+ window.localStorage.setItem('fleetbase_runtime_config_version', '1.0.0');++ clearRuntimeConfigCache();++ assert.strictEqual(window.localStorage.getItem('fleetbase_runtime_config'), null);+ assert.strictEqual(window.localStorage.getItem('fleetbase_runtime_config_version'), null);});});