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
fix(console): clear the metric loading flag when its request fails
Ronald A. Richardson37452f277dac
diff --git a/console/app/components/dashboard/metric.js b/console/app/components/dashboard/metric.jsindex 512ce872..a39fe6e6 100644--- a/console/app/components/dashboard/metric.js+++ b/console/app/components/dashboard/metric.js@@ -27,6 +27,9 @@ export default class MetricComponent extends Component {try {dashboards = yield this.fetch.get(this.args.options.endpoint, params, { namespace: '' });} catch {+ // Clear the flag before bailing out, otherwise a failed request leaves the+ // metric stuck on its loading state for the life of the dashboard.+ this.isLoading = false;return;}diff --git a/console/tests/integration/components/admin/overview-widget-test.js b/console/tests/integration/components/admin/overview-widget-test.jsnew file mode 100644index 00000000..d89fb74e--- /dev/null+++ b/console/tests/integration/components/admin/overview-widget-test.js@@ -0,0 +1,93 @@+import { module, test } from 'qunit';+import { setupRenderingTest } from '@fleetbase/console/tests/helpers';+import { render } from '@ember/test-helpers';+import { hbs } from 'ember-cli-htmlbars';+import Service from '@ember/service';+import AdminOverviewWidgetComponent from '@fleetbase/console/components/admin/overview-widget';+import { captureComponent } from '@fleetbase/console/tests/helpers/capture-component';++module('Integration | Component | admin/overview-widget', function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.requested = [];+ this.kpis = {+ 'metrics/admin/kpis/users-total': { value: 42 },+ 'metrics/admin/kpis/organizations-total': { value: 7 },+ 'metrics/admin/kpis/active-admins': { value: 3 },+ 'metrics/admin/kpis/organizations-attention': { value: 1 },+ };+ this.getRejectsWith = null;+ const context = this;++ class FetchStub extends Service {+ async get(endpoint) {+ context.requested.push(endpoint);++ if (context.getRejectsWith) {+ throw context.getRejectsWith;+ }++ return context.kpis[endpoint];+ }+ }++ this.owner.register('service:fetch', FetchStub);++ const captured = captureComponent(this.owner, 'admin/overview-widget', AdminOverviewWidgetComponent);+ this.build = async () => {+ await render(hbs`<Admin::OverviewWidget />`);+ return captured.instance;+ };+ });++ test('it loads all four KPIs and exposes them as labelled items', async function (assert) {+ const component = await this.build();++ assert.deepEqual(+ this.requested.slice().sort(),+ ['metrics/admin/kpis/active-admins', 'metrics/admin/kpis/organizations-attention', 'metrics/admin/kpis/organizations-total', 'metrics/admin/kpis/users-total'],+ 'every KPI endpoint is requested'+ );+ assert.strictEqual(component.title, 'Admin Overview');+ assert.deepEqual(component.items, [+ { label: 'Users', value: 42 },+ { label: 'Organizations', value: 7 },+ { label: 'Active admins', value: 3 },+ { label: 'Needs attention', value: 1 },+ ]);+ assert.strictEqual(component.error, null, 'no error is recorded on success');+ });++ test('a KPI with no value falls back to zero', async function (assert) {+ this.kpis = {};++ const component = await this.build();++ assert.deepEqual(+ component.items.map((item) => item.value),+ [0, 0, 0, 0],+ 'missing metrics read as zero rather than undefined'+ );+ });++ test('a failed load is surfaced as an error message and the items stay at zero', async function (assert) {+ this.getRejectsWith = new Error('metrics endpoint down');++ const component = await this.build();++ assert.strictEqual(component.error, 'metrics endpoint down', "the failure's own message is shown");+ assert.deepEqual(+ component.items.map((item) => item.value),+ [0, 0, 0, 0]+ );+ });++ test('a failure with no message falls back to a generic one', async function (assert) {+ this.getRejectsWith = {};++ const component = await this.build();++ assert.strictEqual(component.error, 'Unable to load admin overview.');+ });+});diff --git a/console/tests/integration/components/dashboard/metric-test.js b/console/tests/integration/components/dashboard/metric-test.jsnew file mode 100644index 00000000..819c2efd--- /dev/null+++ b/console/tests/integration/components/dashboard/metric-test.js@@ -0,0 +1,82 @@+import { module, test } from 'qunit';+import { setupRenderingTest } from '@fleetbase/console/tests/helpers';+import { render, settled } from '@ember/test-helpers';+import { hbs } from 'ember-cli-htmlbars';+import Service from '@ember/service';+import MetricComponent from '@fleetbase/console/components/dashboard/metric';+import { captureComponent } from '@fleetbase/console/tests/helpers/capture-component';++module('Integration | Component | dashboard/metric', function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.requests = [];+ this.getResponse = [];+ this.getRejectsWith = null;+ const context = this;++ class FetchStub extends Service {+ async get(endpoint, params, options) {+ context.requests.push({ endpoint, params, options });++ if (context.getRejectsWith) {+ throw context.getRejectsWith;+ }++ return context.getResponse;+ }+ }++ this.owner.register('service:fetch', FetchStub);+ this.set('options', { endpoint: 'metrics/orders' });++ const captured = captureComponent(this.owner, 'dashboard/metric', MetricComponent);+ this.build = async () => {+ await render(hbs`<Dashboard::Metric @options={{this.options}} />`);+ return captured.instance;+ };+ });++ test('it loads its dashboard from the configured endpoint on construction', async function (assert) {+ this.getResponse = [{ name: 'Orders' }, { name: 'Ignored' }];++ const component = await this.build();++ assert.deepEqual(this.requests, [{ endpoint: 'metrics/orders', params: undefined, options: { namespace: '' } }], 'the endpoint is called with an empty namespace');+ assert.deepEqual(component.dashboard, { name: 'Orders' }, 'the first dashboard in the response is used');+ assert.false(component.isLoading, 'loading is cleared once the request settles');+ });++ test('a response that is not a list leaves the dashboard unset', async function (assert) {+ this.getResponse = { name: 'not-a-list' };++ const component = await this.build();++ assert.strictEqual(component.dashboard, undefined);+ assert.false(component.isLoading);+ });++ test('a failed request stops loading instead of spinning forever', async function (assert) {+ this.getRejectsWith = new Error('metrics unavailable');++ const component = await this.build();++ assert.strictEqual(component.dashboard, undefined, 'nothing is shown');+ assert.false(component.isLoading, 'the metric does not stay stuck on its loading state');+ });++ test('onQueryParamsChanged reloads the dashboard with the new params', async function (assert) {+ this.getResponse = [{ name: 'Orders' }];+ const component = await this.build();++ this.getResponse = [{ name: 'Filtered' }];+ // The action kicks off the task without returning it, so await settled() rather+ // than awaiting the action itself.+ component.onQueryParamsChanged({ range: '30d' });+ await settled();++ assert.strictEqual(this.requests.length, 2, 'a second request is made');+ assert.deepEqual(this.requests.at(-1).params, { range: '30d' }, 'the changed params are forwarded');+ assert.deepEqual(component.dashboard, { name: 'Filtered' });+ });+});diff --git a/console/tests/integration/components/github-card-test.js b/console/tests/integration/components/github-card-test.jsindex 7fa56445..4e3f7d59 100644--- a/console/tests/integration/components/github-card-test.js+++ b/console/tests/integration/components/github-card-test.js@@ -4,6 +4,8 @@ import { render } from '@ember/test-helpers';import { hbs } from 'ember-cli-htmlbars';import { _resetStorages } from 'ember-local-storage/helpers/storage';import { add } from 'date-fns';+import GithubCardComponent from '@fleetbase/console/components/github-card';+import { captureComponent } from '@fleetbase/console/tests/helpers/capture-component';// Matches config/environment.js: namespace '@fleetbase' + keyDelimiter '/'.const LOCAL_CACHE_KEY = '@fleetbase/storage:local-cache';@@ -53,3 +55,114 @@ module('Integration | Component | github-card', function (hooks) {assert.dom(this.element).containsText('v0.7.53');});});++/**+ * With no live cache the component goes to the GitHub API. ember-fetch delegates to+ * window.fetch in the browser, so swapping that keeps the tests offline and lets the+ * cache-miss branches be driven.+ */+module('Integration | Component | github-card | fetching', function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ _resetStorages();+ window.localStorage.clear();++ this.requested = [];+ // The component imports `fetch` from ember-fetch, which binds self.fetch when the+ // module first evaluates -- swapping window.fetch afterwards has no effect. Babel's+ // AMD interop reads `.default` off the module at each call site, so replace that.+ this.fetchModule = window.require('fetch');+ this.originalFetch = this.fetchModule.default;+ this.responses = {+ 'https://api.github.com/repos/fleetbase/fleetbase': { ok: true, body: { full_name: 'fleetbase/fleetbase' } },+ 'https://api.github.com/repos/fleetbase/fleetbase/tags': { ok: true, body: [{ name: 'v9.9.9' }] },+ };++ this.fetchModule.default = (url) => {+ this.requested.push(url);+ const response = this.responses[url] ?? { ok: false, body: null };++ return Promise.resolve({+ ok: response.ok,+ json: () => Promise.resolve(response.body),+ });+ };+ });++ hooks.afterEach(function () {+ this.fetchModule.default = this.originalFetch;+ _resetStorages();+ window.localStorage.clear();+ });++ test('an empty cache fetches the repository and its tags, then caches both', async function (assert) {+ await render(hbs`<GithubCard />`);++ assert.deepEqual(this.requested.slice().sort(), ['https://api.github.com/repos/fleetbase/fleetbase', 'https://api.github.com/repos/fleetbase/fleetbase/tags']);+ assert.dom(this.element).containsText('fleetbase/fleetbase');+ assert.dom(this.element).containsText('v9.9.9');++ const cache = JSON.parse(window.localStorage.getItem(LOCAL_CACHE_KEY));+ assert.deepEqual(cache['fleetbase-github-data'], { full_name: 'fleetbase/fleetbase' }, 'the repository is cached');+ assert.deepEqual(cache['fleetbase-github-tags'], [{ name: 'v9.9.9' }], 'the tags are cached');+ assert.ok(cache['fleetbase-github-data-expiration'], 'with an expiry stamp');+ assert.ok(cache['fleetbase-github-tags-expiration']);+ });++ test('an expired cache is refetched rather than reused', async function (assert) {+ const expired = add(new Date(), { hours: -1 }).toISOString();+ window.localStorage.setItem(+ LOCAL_CACHE_KEY,+ JSON.stringify({+ 'fleetbase-github-data': { full_name: 'stale/repo' },+ 'fleetbase-github-data-expiration': expired,+ 'fleetbase-github-tags': [{ name: 'v0.0.0-stale' }],+ 'fleetbase-github-tags-expiration': expired,+ })+ );+ _resetStorages();++ await render(hbs`<GithubCard />`);++ assert.strictEqual(this.requested.length, 2, 'both endpoints are refetched');+ assert.dom(this.element).containsText('fleetbase/fleetbase');+ assert.dom(this.element).doesNotContainText('stale/repo');+ });++ test('a failed response leaves the built-in defaults in place', async function (assert) {+ this.responses = {};++ await render(hbs`<GithubCard />`);++ assert.strictEqual(this.requested.length, 2, 'both endpoints were attempted');+ assert.dom('.fleetbase-github-card').exists('the card still renders');+ // latestRelease falls back to v0.0.1 when no tags were loaded.+ assert.dom(this.element).containsText('v0.0.1', 'the placeholder release is shown');+ });++ test('the release link points at the tag when one is known', async function (assert) {+ const captured = captureComponent(this.owner, 'github-card', GithubCardComponent);++ await render(hbs`<GithubCard />`);+ const component = captured.instance;++ assert.deepEqual(component.latestRelease, { name: 'v9.9.9' }, 'the first tag is the latest release');+ assert.strictEqual(component.releaseUrl, 'https://github.com/fleetbase/fleetbase/releases/tag/v9.9.9');++ component.tags = [];+ assert.deepEqual(component.latestRelease, { name: 'v0.0.1' }, 'with no tags a placeholder release is used');+ assert.strictEqual(component.releaseUrl, 'https://github.com/fleetbase/fleetbase/releases/tag/v0.0.1');+ });++ test('the release link drops the tag segment when the release has no name', async function (assert) {+ const captured = captureComponent(this.owner, 'github-card', GithubCardComponent);++ await render(hbs`<GithubCard />`);+ const component = captured.instance;++ component.tags = [{ name: '' }];++ assert.strictEqual(component.releaseUrl, 'https://github.com/fleetbase/fleetbase/releases', 'a blank tag name leaves the plain releases URL');+ });+});diff --git a/console/tests/integration/components/modals/validate-password-test.js b/console/tests/integration/components/modals/validate-password-test.jsindex 5978dccd..9c13bc61 100644--- a/console/tests/integration/components/modals/validate-password-test.js+++ b/console/tests/integration/components/modals/validate-password-test.js@@ -3,6 +3,8 @@ import { setupRenderingTest } from '@fleetbase/console/tests/helpers';import { render } from '@ember/test-helpers';import { hbs } from 'ember-cli-htmlbars';import Service from '@ember/service';+import ModalsValidatePasswordComponent from '@fleetbase/console/components/modals/validate-password';+import { captureComponent } from '@fleetbase/console/tests/helpers/capture-component';module('Integration | Component | modals/validate-password', function (hooks) {setupRenderingTest(hooks);@@ -42,3 +44,96 @@ module('Integration | Component | modals/validate-password', function (hooks) {assert.strictEqual(typeof this.options.confirm, 'function', 'a confirm handler is installed');});});++/**+ * The validation task is invoked by the modal's confirm handler, which the modals manager+ * normally supplies, so drive it on the captured instance.+ */+module('Integration | Component | modals/validate-password | task', function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.posted = [];+ this.postRejectsWith = null;+ const context = this;++ class FetchStub extends Service {+ async post(path, payload) {+ context.posted.push({ path, payload });++ if (context.postRejectsWith) {+ throw context.postRejectsWith;+ }++ return { valid: true };+ }+ }+ class NotificationsStub extends Service {+ serverErrors = [];+ success() {}+ error() {}+ serverError(error, message) {+ this.serverErrors.push([error, message]);+ }+ }+ this.owner.register('service:fetch', FetchStub);+ this.owner.register('service:notifications', NotificationsStub);++ const captured = captureComponent(this.owner, 'modals/validate-password', ModalsValidatePasswordComponent);+ this.build = async () => {+ await render(hbs`<Modals::ValidatePassword @modalIsOpened={{true}} @options={{this.options}} />`);+ return captured.instance;+ };+ });++ test('a valid password posts both fields and reports success', async function (assert) {+ const validated = [];+ this.set('options', { onValidated: (result) => validated.push(result) });+ const component = await this.build();++ component.password = 'current-secret';+ component.confirmPassword = 'current-secret';++ const result = await component.validatePassword.perform();++ assert.deepEqual(this.posted, [{ path: 'users/validate-password', payload: { password: 'current-secret', password_confirmation: 'current-secret' } }]);+ assert.true(result);+ assert.deepEqual(validated, [true], 'the caller is told the password checked out');+ });++ test('a rejected password is reported and returns false', async function (assert) {+ const validated = [];+ this.set('options', { onValidated: (result) => validated.push(result) });+ const failure = new Error('wrong password');+ this.postRejectsWith = failure;+ const component = await this.build();++ const result = await component.validatePassword.perform();++ assert.false(result);+ assert.deepEqual(this.owner.lookup('service:notifications').serverErrors, [[failure, 'Invalid current password.']]);+ assert.deepEqual(validated, [false]);+ });++ test('it validates happily when no onValidated callback was supplied', async function (assert) {+ this.set('options', {});+ const component = await this.build();++ const result = await component.validatePassword.perform();++ assert.true(result, 'the result is still returned to the caller');+ });++ test('the installed confirm handler puts the modal into its loading state', async function (assert) {+ this.set('options', {});+ const component = await this.build();+ const calls = [];++ const result = await this.options.confirm({ startLoading: () => calls.push('startLoading') });++ assert.deepEqual(calls, ['startLoading'], 'the modal is told to show its spinner');+ assert.true(result, 'and the validation result is handed back to the modal');+ assert.strictEqual(this.posted.at(-1).path, 'users/validate-password');+ assert.strictEqual(component.options, this.options, 'the component works against the options object it was given');+ });+});diff --git a/console/tests/integration/components/onboarding/form-test.js b/console/tests/integration/components/onboarding/form-test.jsindex 2909587c..e85e7ac5 100644--- a/console/tests/integration/components/onboarding/form-test.js+++ b/console/tests/integration/components/onboarding/form-test.js@@ -2,6 +2,9 @@ import { module, test } from 'qunit';import { setupRenderingTest } from '@fleetbase/console/tests/helpers';import { render, fillIn } from '@ember/test-helpers';import { hbs } from 'ember-cli-htmlbars';+import Service from '@ember/service';+import OnboardingFormComponent from '@fleetbase/console/components/onboarding/form';+import { captureComponent } from '@fleetbase/console/tests/helpers/capture-component';module('Integration | Component | onboarding/form', function (hooks) {setupRenderingTest(hooks);@@ -42,3 +45,206 @@ module('Integration | Component | onboarding/form', function (hooks) {assert.dom('img').exists('the brand logo renders');});});++/**+ * The onboard task runs behind a submit button that stays disabled until every field is+ * filled, and `phone` is only reachable through PhoneInput's @onInput, so drive the task+ * on the captured instance instead of through the DOM.+ */+module('Integration | Component | onboarding/form | onboard', function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.owner.lookup('service:intl').setLocale('en-us');++ this.posted = [];+ this.postResponse = { status: 'success', session: 'session-token' };+ this.postRejectsWith = null;+ this.persisted = [];+ this.orchestratorCalls = [];+ const context = this;++ class FetchStub extends Service {+ async post(path, payload) {+ context.posted.push({ path, payload });++ if (context.postRejectsWith) {+ throw context.postRejectsWith;+ }++ return context.postResponse;+ }+ }+ class NotificationsStub extends Service {+ errors = [];+ successes = [];+ serverErrors = [];+ error(message) {+ this.errors.push(message);+ }+ success(message) {+ this.successes.push(message);+ }+ serverError(error) {+ this.serverErrors.push(error);+ }+ }+ class SessionStub extends Service {+ authenticated = [];+ isOnboarding() {+ return {+ manuallyAuthenticate: (token) => this.authenticated.push(token),+ };+ }+ }++ this.owner.register('service:fetch', FetchStub);+ this.owner.register('service:notifications', NotificationsStub);+ this.owner.register('service:session', SessionStub);++ this.set('context', { persist: (key, value) => this.persisted.push([key, value]) });+ this.set('orchestrator', {+ current: { id: 'verify-email' },+ next: () => this.orchestratorCalls.push('next'),+ });++ const captured = captureComponent(this.owner, 'onboarding/form', OnboardingFormComponent);+ this.build = async () => {+ await render(hbs`<Onboarding::Form @context={{this.context}} @orchestrator={{this.orchestrator}} />`);+ const component = captured.instance;++ // The router is built in and cannot be swapped through owner.register.+ this.transitions = [];+ Object.defineProperty(component.router, 'transitionTo', {+ configurable: true,+ value: (routeName) => {+ this.transitions.push(routeName);+ return Promise.resolve(routeName);+ },+ });+ this.urlParams = [];+ Object.defineProperty(component.urlSearchParams, 'setParamsToCurrentUrl', {+ configurable: true,+ value: (params) => this.urlParams.push(params),+ });++ return component;+ };++ this.fillValidly = (component) => {+ component.name = 'Ron Richardson';+ component.email = '[email protected]';+ component.phone = '+15551234567';+ component.organization_name = 'Fleetbase';+ component.password = 'super-secret-password';+ component.password_confirmation = 'super-secret-password';+ };+ this.notifications = () => this.owner.lookup('service:notifications');+ });++ test('filled only reports true once every field has a value', async function (assert) {+ const component = await this.build();++ assert.false(component.filled, 'an empty form is not ready');++ this.fillValidly(component);+ assert.true(component.filled);++ component.phone = '';+ assert.false(component.filled, 'a blank phone number blocks submission');+ });++ test('onboard reports the first validation failure and sends nothing', async function (assert) {+ const component = await this.build();++ await component.onboard.perform();++ assert.deepEqual(this.posted, [], 'no account is created');+ assert.strictEqual(this.notifications().errors.length, 1, 'a validation message is shown');+ assert.ok(this.notifications().errors[0], 'the message is not empty');+ });++ test('onboard rejects a password confirmation that does not match', async function (assert) {+ const component = await this.build();+ this.fillValidly(component);+ component.password_confirmation = 'something-else';++ await component.onboard.perform();++ assert.deepEqual(this.posted, [], 'no account is created');+ assert.strictEqual(this.notifications().errors.length, 1);+ });++ test('onboard prevents the default form submission', async function (assert) {+ const component = await this.build();+ let prevented = false;++ await component.onboard.perform({ preventDefault: () => (prevented = true) });++ assert.true(prevented, 'the browser does not navigate away');+ });++ test('onboard posts the account with the resolved timezone and advances the flow', async function (assert) {+ const component = await this.build();+ this.fillValidly(component);++ await component.onboard.perform();++ const { path, payload } = this.posted.at(-1);+ assert.strictEqual(path, 'onboard/create-account');+ assert.strictEqual(payload.email, '[email protected]');+ assert.strictEqual(payload.organization_name, 'Fleetbase');+ assert.strictEqual(payload.timezone, Intl.DateTimeFormat().resolvedOptions().timeZone, 'the browser timezone is sent along');+ assert.deepEqual(this.persisted, [['session', 'session-token']], 'the session is persisted for the next step');+ assert.deepEqual(this.orchestratorCalls, ['next'], 'the onboarding flow advances');+ assert.deepEqual(this.urlParams, [{ step: 'verify-email', session: 'session-token' }], 'the URL records where the flow is up to');+ assert.deepEqual(this.transitions, [], 'the user stays in the onboarding flow');+ });++ test('onboard signs the user straight in when verification is skipped', async function (assert) {+ this.postResponse = { status: 'success', session: 'session-token', skipVerification: true, token: 'auth-token' };+ const component = await this.build();+ this.fillValidly(component);++ await component.onboard.perform();++ assert.deepEqual(this.owner.lookup('service:session').authenticated, ['auth-token']);+ assert.deepEqual(this.transitions, ['console'], 'the user lands in the console');+ assert.deepEqual(this.notifications().successes, ['Welcome to Fleetbase!']);+ assert.deepEqual(this.orchestratorCalls, [], 'the onboarding flow is not advanced');+ });++ test('onboard stays in the flow when a token is missing despite skipVerification', async function (assert) {+ this.postResponse = { status: 'success', session: 'session-token', skipVerification: true };+ const component = await this.build();+ this.fillValidly(component);++ await component.onboard.perform();++ assert.deepEqual(this.transitions, [], 'without a token there is nothing to authenticate with');+ assert.deepEqual(this.orchestratorCalls, ['next'], 'so the verification step is used instead');+ });++ test('onboard reports an unsuccessful status and stops', async function (assert) {+ this.postResponse = { status: 'failed' };+ const component = await this.build();+ this.fillValidly(component);++ await component.onboard.perform();++ assert.deepEqual(this.notifications().errors, ['Onboard failed']);+ assert.deepEqual(this.persisted, [], 'no session is stored');+ assert.deepEqual(this.orchestratorCalls, []);+ });++ test('onboard surfaces a failed request as a server error', async function (assert) {+ const failure = new Error('signup service unavailable');+ this.postRejectsWith = failure;+ const component = await this.build();+ this.fillValidly(component);++ await component.onboard.perform();++ assert.deepEqual(this.notifications().serverErrors, [failure]);+ });+});diff --git a/console/tests/integration/components/two-fa-settings-test.js b/console/tests/integration/components/two-fa-settings-test.jsindex 5dd57be9..665bf25b 100644--- a/console/tests/integration/components/two-fa-settings-test.js+++ b/console/tests/integration/components/two-fa-settings-test.js@@ -2,6 +2,8 @@ import { module, test } from 'qunit';import { setupRenderingTest } from '@fleetbase/console/tests/helpers';import { render } from '@ember/test-helpers';import { hbs } from 'ember-cli-htmlbars';+import TwoFaSettingsComponent from '@fleetbase/console/components/two-fa-settings';+import { captureComponent } from '@fleetbase/console/tests/helpers/capture-component';module('Integration | Component | two-fa-settings', function (hooks) {setupRenderingTest(hooks);@@ -48,3 +50,144 @@ module('Integration | Component | two-fa-settings', function (hooks) {assert.dom(this.element).doesNotContainText('Choose an authentication method');});});++/**+ * The toggle and selection handlers are wired to third-party toggle components, so drive+ * them on the captured instance instead of through the DOM.+ */+module('Integration | Component | two-fa-settings | actions', function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.set('methods', [+ { key: 'email', name: 'Email' },+ { key: 'sms', name: 'SMS', recommended: true },+ ]);+ this.set('settings', { enabled: false });+ this.calls = [];+ this.set('onTwoFaToggled', (...args) => this.calls.push(['toggled', ...args]));+ this.set('onTwoFaMethodSelected', (...args) => this.calls.push(['method', ...args]));+ this.set('onTwoFaEnforcedToggled', (...args) => this.calls.push(['enforced', ...args]));++ const captured = captureComponent(this.owner, 'two-fa-settings', TwoFaSettingsComponent);+ this.build = async () => {+ await render(hbs`+ <TwoFaSettings+ @twoFaSettings={{this.settings}}+ @twoFaMethods={{this.methods}}+ @showEnforceOption={{true}}+ @onTwoFaToggled={{this.onTwoFaToggled}}+ @onTwoFaMethodSelected={{this.onTwoFaMethodSelected}}+ @onTwoFaEnforcedToggled={{this.onTwoFaEnforcedToggled}}+ />+ `);+ return captured.instance;+ };+ this.buildBare = async () => {+ await render(hbs`<TwoFaSettings @twoFaSettings={{this.settings}} @twoFaMethods={{this.methods}} />`);+ return captured.instance;+ };+ });++ test('it adopts the stored method and flags when they are set', async function (assert) {+ this.set('settings', { enabled: true, enforced: true, method: 'sms' });++ const component = await this.build();++ assert.true(component.isTwoFaEnabled);+ assert.true(component.isTwoFaEnforced);+ assert.true(component.showEnforceOption);+ assert.true(component.showMethodSelection, 'method selection is on unless explicitly disabled');+ assert.strictEqual(component.selectedTwoFaMethod, 'sms');+ });++ test('an unrecognised stored method falls back to email', async function (assert) {+ this.set('settings', { enabled: true, method: 'carrier-pigeon' });++ const component = await this.build();++ assert.strictEqual(component.selectedTwoFaMethod, 'email');+ });++ test('a missing method list falls back to email', async function (assert) {+ this.set('methods', undefined);+ this.set('settings', { enabled: true, method: 'sms' });++ const component = await this.build();++ assert.strictEqual(component.selectedTwoFaMethod, 'email', 'with no methods to match against, the default is used');+ });++ test('enabling 2FA selects the recommended method and reports both changes', async function (assert) {+ const component = await this.build();++ component.onTwoFaToggled(true);++ assert.true(component.isTwoFaEnabled);+ assert.strictEqual(component.selectedTwoFaMethod, 'sms', 'the recommended method is pre-selected');+ assert.deepEqual(this.calls, [+ ['toggled', true],+ ['method', 'sms'],+ ]);+ });++ test('enabling 2FA with no recommended method keeps the current selection', async function (assert) {+ this.set('methods', [{ key: 'email', name: 'Email' }]);+ const component = await this.build();++ component.onTwoFaToggled(true);++ assert.strictEqual(component.selectedTwoFaMethod, 'email', 'nothing is recommended, so the existing choice stands');+ });++ test('disabling 2FA clears the selected method', async function (assert) {+ this.set('settings', { enabled: true, method: 'sms' });+ const component = await this.build();++ component.onTwoFaToggled(false);++ assert.false(component.isTwoFaEnabled);+ assert.strictEqual(component.selectedTwoFaMethod, null);+ assert.deepEqual(this.calls, [+ ['toggled', false],+ ['method', null],+ ]);+ });++ test('toggling works without any callbacks wired up', async function (assert) {+ const component = await this.buildBare();++ component.onTwoFaToggled(true);+ component.onTwoFaSelected('email');+ component.onTwoFaEnforcedToggled(true);+ component.onRequireUsersToSetUpToggled(false);++ assert.true(component.isTwoFaEnabled, 'state still updates with no listeners attached');+ assert.strictEqual(component.selectedTwoFaMethod, 'email');+ assert.false(component.isTwoFaEnforced);+ });++ test('selecting a method records it and reports the choice', async function (assert) {+ const component = await this.build();++ component.onTwoFaSelected('email');++ assert.strictEqual(component.selectedTwoFaMethod, 'email');+ assert.deepEqual(this.calls, [['method', 'email']]);+ });++ test('both enforcement toggles update the flag and report it', async function (assert) {+ const component = await this.build();++ component.onTwoFaEnforcedToggled(true);+ assert.true(component.isTwoFaEnforced);++ component.onRequireUsersToSetUpToggled(false);+ assert.false(component.isTwoFaEnforced);++ assert.deepEqual(this.calls, [+ ['enforced', true],+ ['enforced', false],+ ]);+ });+});