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 configure component actions via captured instances
Ronald A. Richardsond0dc750089f0
diff --git a/console/tests/helpers/capture-component.js b/console/tests/helpers/capture-component.jsnew file mode 100644index 00000000..a941fc3c--- /dev/null+++ b/console/tests/helpers/capture-component.js@@ -0,0 +1,38 @@+/**+ * Hands a test the live instance of a Glimmer component.+ *+ * Glimmer components cannot be constructed by hand: the debug build checks the `args`+ * object against an internal WeakSet, so `new MyComponent(owner, {})` throws "You must pass+ * both the owner and args to super()". The supported way to reach an instance is to let+ * Ember build it, so this registers a capturing subclass under the component's own name.+ * The subclass adds nothing but a constructor hook — the real class still supplies every+ * method under test, and its template comes along because getComponentTemplate() walks the+ * prototype chain.+ *+ * Register before rendering, then read `.instance` afterwards:+ *+ * const captured = captureComponent(this.owner, 'configure/queue', ConfigureQueueComponent);+ * await render(hbs`<Configure::Queue />`);+ * captured.instance.setDriver('sqs');+ *+ * @param {Owner} owner The test container owner+ * @param {String} name The component name as registered, e.g. 'configure/queue'+ * @param {Class} ComponentClass The real component class to instantiate+ * @return {{ instance: Object|null }} A box whose `instance` is filled in on render+ */+export function captureComponent(owner, name, ComponentClass) {+ const captured = { instance: null };++ class CapturingComponent extends ComponentClass {+ constructor() {+ super(...arguments);+ captured.instance = this;+ }+ }++ owner.register(`component:${name}`, CapturingComponent);++ return captured;+}++export default captureComponent;diff --git a/console/tests/integration/components/configure/filesystem-test.js b/console/tests/integration/components/configure/filesystem-test.jsindex f8a20895..d768ec13 100644--- a/console/tests/integration/components/configure/filesystem-test.js+++ b/console/tests/integration/components/configure/filesystem-test.js@@ -3,31 +3,74 @@ import { setupRenderingTest } from '@fleetbase/console/tests/helpers';import { render, click } from '@ember/test-helpers';import { hbs } from 'ember-cli-htmlbars';import Service from '@ember/service';+import ConfigureFilesystemComponent from '@fleetbase/console/components/configure/filesystem';+import { captureComponent } from '@fleetbase/console/tests/helpers/capture-component';++/**+ * Lets the fire-and-forget promise chains the component kicks off in its constructor and+ * actions run to completion. They are native promises, so settled() does not track them.+ */+function flush() {+ return new Promise((resolve) => setTimeout(resolve, 0));+}module('Integration | Component | configure/filesystem', function (hooks) {setupRenderingTest(hooks);hooks.beforeEach(function () {this.posted = [];- const posted = this.posted;+ this.uploads = [];+ this.getResponse = { driver: 'local', disks: ['local', 's3', 'gcs'] };+ this.postResponse = { status: 'ok', message: 'Connection successful' };+ const context = this;class FetchStub extends Service {get() {- return Promise.resolve({ driver: 'local', disks: ['local', 's3', 'gcs'] });+ return Promise.resolve(context.getResponse);}post(path, payload) {- posted.push({ path, payload });- return Promise.resolve({ status: 'ok', message: 'Connection successful' });+ context.posted.push({ path, payload });+ return Promise.resolve(context.postResponse);}+ uploadFile = {+ perform: (file, meta, onUploaded) => {+ context.uploads.push({ file, meta });++ if (context.uploadThrows) {+ throw context.uploadThrows;+ }++ onUploaded({ id: 'file_1', path: 'gcs/creds.json' });+ },+ };}class NotificationsStub extends Service {- success() {}+ successes = [];+ serverErrors = [];+ success(message) {+ this.successes.push(message);+ }error() {}- serverError() {}+ serverError(error) {+ this.serverErrors.push(error);+ }}this.owner.register('service:fetch', FetchStub);this.owner.register('service:notifications', NotificationsStub);++ // Glimmer components cannot be constructed by hand, so let Ember build one and+ // capture it: the actions below are only reachable through third-party controls+ // in the template, or not rendered at all.+ const captured = captureComponent(this.owner, 'configure/filesystem', ConfigureFilesystemComponent);+ this.build = async () => {+ await render(hbs`+ <div id="next-view-section-subheader-actions"></div>+ <Configure::Filesystem />+ `);+ await flush();+ return captured.instance;+ };});test('it renders the filesystem panel and wormholes its save button to the subheader', async function (assert) {@@ -64,4 +107,112 @@ module('Integration | Component | configure/filesystem', function (hooks) {assert.strictEqual(this.posted.at(-1).path, 'settings/filesystem-config');assert.strictEqual(this.posted.at(-1).payload.driver, 'local');});++ test('it starts on the local driver with no storage configured', async function (assert) {+ this.getResponse = {};+ const component = await this.build();++ assert.strictEqual(component.driver, 'local');+ assert.deepEqual(component.disks, []);+ // Read before anything writes them: a @tracked field's initializer only runs on+ // first access, so a test that assigns first never evaluates it.+ assert.strictEqual(component.testResponse, undefined, 'no connection test has run yet');+ assert.strictEqual(component.s3Url, null);+ assert.strictEqual(component.s3Endpoint, null);+ assert.strictEqual(component.gcsCredentialsFileId, null);+ assert.strictEqual(component.gcsCredentialsFile, null);+ assert.strictEqual(component.s3Bucket, null);+ assert.strictEqual(component.gcsBucket, null);+ assert.false(component.isGoogleCloudStorageEnvConfigued);+ assert.false(component.isLoading, 'loading is cleared once the config request settles');+ });++ test('loadConfigValues applies known keys and ignores unknown ones', async function (assert) {+ this.getResponse = { driver: 's3', s3Bucket: 'my-bucket', notAFieldOnThisComponent: 'ignored' };+ const component = await this.build();++ assert.strictEqual(component.driver, 's3');+ assert.strictEqual(component.s3Bucket, 'my-bucket');+ assert.strictEqual(component.notAFieldOnThisComponent, undefined, 'keys the component does not declare are dropped');+ });++ test('setDriver swaps the active driver', async function (assert) {+ const component = await this.build();++ component.setDriver('gcs');++ assert.strictEqual(component.driver, 'gcs');+ });++ test('save posts the s3 and gcs settings and reports success', async function (assert) {+ this.getResponse = {};+ const component = await this.build();++ component.setDriver('s3');+ component.s3Bucket = 'bucket';+ component.s3Url = 'https://cdn.example.com';+ component.s3Endpoint = 'https://s3.example.com';+ component.gcsBucket = 'gcs-bucket';+ component.gcsCredentialsFileId = 'file_1';++ component.save();+ assert.true(component.isLoading, 'the panel is busy while saving');+ await flush();++ const { path, payload } = this.posted.at(-1);+ assert.strictEqual(path, 'settings/filesystem-config');+ assert.strictEqual(payload.driver, 's3');+ assert.deepEqual(payload.s3, { bucket: 'bucket', url: 'https://cdn.example.com', endpoint: 'https://s3.example.com' });+ assert.strictEqual(payload.gcsBucket, 'gcs-bucket');+ assert.strictEqual(payload.gcsCredentialsFileId, 'file_1');+ assert.deepEqual(this.owner.lookup('service:notifications').successes, ['Filesystem configuration saved.']);+ assert.false(component.isLoading);+ });++ test('test posts the selected disk and keeps the response', async function (assert) {+ const component = await this.build();++ component.setDriver('s3');+ component.test();+ await flush();++ assert.deepEqual(this.posted.at(-1), { path: 'settings/test-filesystem-config', payload: { disk: 's3' } });+ assert.deepEqual(component.testResponse, this.postResponse);+ assert.false(component.isLoading);+ });++ test('uploading gcs credentials stores the returned file', async function (assert) {+ const component = await this.build();++ component.uploadGcsCredentialsFile({ name: 'creds.json' });++ assert.strictEqual(this.uploads[0].meta.path, 'gcs');+ assert.strictEqual(this.uploads[0].meta.type, 'gcs_credentials');+ assert.strictEqual(this.uploads[0].meta.subject_type, 'company');+ assert.strictEqual(component.gcsCredentialsFileId, 'file_1');+ assert.deepEqual(component.gcsCredentialsFile, { id: 'file_1', path: 'gcs/creds.json' });+ });++ test('a failed gcs upload is reported rather than thrown', async function (assert) {+ const failure = new Error('upload rejected');+ this.uploadThrows = failure;+ const component = await this.build();++ component.uploadGcsCredentialsFile({ name: 'creds.json' });++ assert.deepEqual(this.owner.lookup('service:notifications').serverErrors, [failure]);+ assert.strictEqual(component.gcsCredentialsFileId, null, 'nothing is stored when the upload fails');+ });++ test('removeGcsCredentialsFile clears both the file and its id', async function (assert) {+ const component = await this.build();++ component.uploadGcsCredentialsFile({ name: 'creds.json' });+ assert.strictEqual(component.gcsCredentialsFileId, 'file_1', 'precondition: a file is attached');++ component.removeGcsCredentialsFile();++ assert.strictEqual(component.gcsCredentialsFileId, undefined);+ assert.strictEqual(component.gcsCredentialsFile, undefined);+ });});diff --git a/console/tests/integration/components/configure/notification-channels-test.js b/console/tests/integration/components/configure/notification-channels-test.jsindex 492163c6..3f403184 100644--- a/console/tests/integration/components/configure/notification-channels-test.js+++ b/console/tests/integration/components/configure/notification-channels-test.js@@ -3,31 +3,74 @@ import { setupRenderingTest } from '@fleetbase/console/tests/helpers';import { render, click } from '@ember/test-helpers';import { hbs } from 'ember-cli-htmlbars';import Service from '@ember/service';+import ConfigureNotificationChannelsComponent from '@fleetbase/console/components/configure/notification-channels';+import { captureComponent } from '@fleetbase/console/tests/helpers/capture-component';++/**+ * Lets the fire-and-forget promise chains the component starts run to completion. They are+ * native promises, so settled() does not track them.+ */+function flush() {+ return new Promise((resolve) => setTimeout(resolve, 0));+}module('Integration | Component | configure/notification-channels', function (hooks) {setupRenderingTest(hooks);hooks.beforeEach(function () {this.posted = [];- const posted = this.posted;+ this.uploads = [];+ this.getResponse = {};+ this.postResponse = { status: 'ok' };+ const context = this;class FetchStub extends Service {get() {- return Promise.resolve({});+ return Promise.resolve(context.getResponse);}post(path, payload) {- posted.push({ path, payload });- return Promise.resolve({ status: 'ok' });+ context.posted.push({ path, payload });+ return Promise.resolve(context.postResponse);}+ uploadFile = {+ perform: (file, meta, onUploaded) => {+ context.uploads.push({ file, meta });++ if (context.uploadThrows) {+ throw context.uploadThrows;+ }++ onUploaded(context.uploadedFile ?? { id: 'file_1', path: 'apn/key.p8' });+ },+ };}class NotificationsStub extends Service {- success() {}+ successes = [];+ serverErrors = [];+ success(message) {+ this.successes.push(message);+ }error() {}- serverError() {}+ serverError(error) {+ this.serverErrors.push(error);+ }}this.owner.register('service:fetch', FetchStub);this.owner.register('service:notifications', NotificationsStub);++ // Glimmer components cannot be constructed by hand, so let Ember build one and+ // capture it: the actions below are only reachable through third-party controls+ // in the template, or not rendered at all.+ const captured = captureComponent(this.owner, 'configure/notification-channels', ConfigureNotificationChannelsComponent);+ this.build = async () => {+ await render(hbs`+ <div id="next-view-section-subheader-actions"></div>+ <Configure::NotificationChannels />+ `);+ await flush();+ return captured.instance;+ };});test('it renders the APN, Firebase and test panels', async function (assert) {@@ -53,4 +96,166 @@ module('Integration | Component | configure/notification-channels', function (hoassert.strictEqual(this.posted.at(-1).path, 'settings/notification-channels-config');});++ test('it starts with an empty APN config and a prefilled test notification', async function (assert) {+ const component = await this.build();++ // Read before anything writes them: a @tracked field's initializer only runs on+ // first access, so a test that assigns first never evaluates it.+ assert.strictEqual(component.testResponse, undefined, 'no test notification has been sent yet');+ assert.strictEqual(component.testTitle, 'Hello World from Fleetbase 🚀');+ assert.strictEqual(component.testMessage, 'This is a test push notification!');+ assert.strictEqual(component.apnToken, undefined);+ assert.strictEqual(component.fcmToken, undefined);+ assert.true(component.apn.production, 'APN defaults to the production gateway');+ assert.strictEqual(component.apn.key_id, '');+ assert.deepEqual(component.firebase, { credentials: '' });+ assert.false(component.isLoading);+ });++ test('loadConfigValues applies known keys and ignores unknown ones', async function (assert) {+ this.getResponse = {+ apn: { key_id: 'ABC123', production: false },+ testTitle: 'Loaded title',+ notAFieldOnThisComponent: 'ignored',+ };+ const component = await this.build();++ assert.strictEqual(component.apn.key_id, 'ABC123');+ assert.strictEqual(component.testTitle, 'Loaded title');+ assert.strictEqual(component.notAFieldOnThisComponent, undefined, 'keys the component does not declare are dropped');+ });++ test('toggleApnProduction switches the gateway without dropping the rest of the config', async function (assert) {+ const component = await this.build();++ component.apn = { ...component.apn, key_id: 'ABC123' };+ component.toggleApnProduction(false);++ assert.false(component.apn.production);+ assert.strictEqual(component.apn.key_id, 'ABC123', 'the other APN fields survive the toggle');++ component.toggleApnProduction(true);+ assert.true(component.apn.production);+ });++ test('uploading an APN key records it against the company', async function (assert) {+ this.uploadedFile = { id: 'apn_1', path: 'apn/AuthKey.p8' };+ const component = await this.build();++ component.uploadApnKey({ name: 'AuthKey.p8' });++ assert.strictEqual(this.uploads[0].meta.path, 'apn');+ assert.strictEqual(this.uploads[0].meta.type, 'apn_key');+ assert.strictEqual(this.uploads[0].meta.subject_type, 'company');+ assert.strictEqual(component.apn.private_key_file_id, 'apn_1');+ assert.strictEqual(component.apn.private_key_path, 'apn/AuthKey.p8');+ assert.strictEqual(component.apn._private_key_path, 'apn/AuthKey.p8');+ assert.deepEqual(component.apn.private_key_file, this.uploadedFile);+ });++ test('a failed APN key upload is reported rather than thrown', async function (assert) {+ const failure = new Error('upload rejected');+ this.uploadThrows = failure;+ const component = await this.build();++ component.uploadApnKey({ name: 'AuthKey.p8' });++ assert.deepEqual(this.owner.lookup('service:notifications').serverErrors, [failure]);+ assert.strictEqual(component.apn.private_key_file_id, '', 'nothing is recorded when the upload fails');+ });++ test('removeApnFile clears every trace of the uploaded key', async function (assert) {+ const component = await this.build();++ component.uploadApnKey({ name: 'AuthKey.p8' });+ assert.strictEqual(component.apn.private_key_file_id, 'file_1', 'precondition: a key is attached');++ component.removeApnFile();++ assert.strictEqual(component.apn.private_key_file, null);+ assert.strictEqual(component.apn.private_key_file_id, '');+ assert.strictEqual(component.apn.private_key_path, '');+ assert.strictEqual(component.apn._private_key_path, '');+ });++ test('uploading Firebase credentials records them against the company', async function (assert) {+ this.uploadedFile = { id: 'fb_1', path: 'firebase/creds.json' };+ const component = await this.build();++ component.uploadFirebaseCredentials({ name: 'creds.json' });++ assert.strictEqual(this.uploads[0].meta.path, 'firebase');+ assert.strictEqual(this.uploads[0].meta.type, 'firebase_credentials');+ assert.strictEqual(component.firebase.credentials_file_id, 'fb_1');+ assert.strictEqual(component.firebase.credentials_file_path, 'firebase/creds.json');+ assert.deepEqual(component.firebase.credentials_file, this.uploadedFile);+ });++ test('a failed Firebase upload is reported rather than thrown', async function (assert) {+ const failure = new Error('upload rejected');+ this.uploadThrows = failure;+ const component = await this.build();++ component.uploadFirebaseCredentials({ name: 'creds.json' });++ assert.deepEqual(this.owner.lookup('service:notifications').serverErrors, [failure]);+ assert.strictEqual(component.firebase.credentials_file_id, undefined, 'nothing is recorded when the upload fails');+ });++ test('removeFirebaseCredentialsFile clears the stored credentials', async function (assert) {+ const component = await this.build();++ component.uploadFirebaseCredentials({ name: 'creds.json' });+ assert.strictEqual(component.firebase.credentials_file_id, 'file_1', 'precondition: credentials are attached');++ component.removeFirebaseCredentialsFile();++ assert.strictEqual(component.firebase.credentials_file, null);+ assert.strictEqual(component.firebase.credentials_file_id, '');+ assert.strictEqual(component.firebase.credentials, '');+ });++ test('save strips the file handles before posting and reports success', async function (assert) {+ const component = await this.build();++ component.uploadApnKey({ name: 'AuthKey.p8' });+ component.uploadFirebaseCredentials({ name: 'creds.json' });++ component.save();+ assert.true(component.isLoading, 'the panel is busy while saving');+ await flush();++ const { path, payload } = this.posted.at(-1);+ assert.strictEqual(path, 'settings/notification-channels-config');+ assert.false('private_key_file' in payload.apn, 'the APN file handle is not sent');+ assert.false('credentials_file' in payload.firebase, 'the Firebase file handle is not sent');+ assert.strictEqual(payload.apn.private_key_file_id, 'file_1', 'but the uploaded file id is');+ assert.deepEqual(this.owner.lookup('service:notifications').successes, ["Notification channel's configuration saved."]);+ assert.false(component.isLoading);+ });++ test('test posts the notification payload and keeps the response', async function (assert) {+ this.postResponse = { status: 'ok', delivered: 2 };+ const component = await this.build();++ component.testTitle = 'Ping';+ component.testMessage = 'Are you there?';+ component.apnToken = 'apn-token';+ component.fcmToken = 'fcm-token';++ component.test();+ assert.true(component.isLoading);+ await flush();++ const { path, payload } = this.posted.at(-1);+ assert.strictEqual(path, 'settings/test-notification-channels-config');+ assert.strictEqual(payload.title, 'Ping');+ assert.strictEqual(payload.message, 'Are you there?');+ assert.strictEqual(payload.apnToken, 'apn-token');+ assert.strictEqual(payload.fcmToken, 'fcm-token');+ assert.deepEqual(payload.apn, component.apn);+ assert.deepEqual(component.testResponse, this.postResponse);+ assert.false(component.isLoading);+ });});diff --git a/console/tests/integration/components/configure/queue-test.js b/console/tests/integration/components/configure/queue-test.jsindex 47330b37..93cbfa9f 100644--- a/console/tests/integration/components/configure/queue-test.js+++ b/console/tests/integration/components/configure/queue-test.js@@ -3,31 +3,59 @@ import { setupRenderingTest } from '@fleetbase/console/tests/helpers';import { render, click } from '@ember/test-helpers';import { hbs } from 'ember-cli-htmlbars';import Service from '@ember/service';+import ConfigureQueueComponent from '@fleetbase/console/components/configure/queue';+import { captureComponent } from '@fleetbase/console/tests/helpers/capture-component';++/**+ * Lets the fire-and-forget promise chains the component starts run to completion. They are+ * native promises, so settled() does not track them.+ */+function flush() {+ return new Promise((resolve) => setTimeout(resolve, 0));+}module('Integration | Component | configure/queue', function (hooks) {setupRenderingTest(hooks);hooks.beforeEach(function () {this.posted = [];- const posted = this.posted;+ this.getResponse = { driver: 'redis' };+ this.postResponse = { status: 'ok' };+ const context = this;class FetchStub extends Service {get() {- return Promise.resolve({ driver: 'redis' });+ return Promise.resolve(context.getResponse);}post(path, payload) {- posted.push({ path, payload });- return Promise.resolve({ status: 'ok' });+ context.posted.push({ path, payload });+ return Promise.resolve(context.postResponse);}}class NotificationsStub extends Service {- success() {}+ successes = [];+ success(message) {+ this.successes.push(message);+ }error() {}serverError() {}}this.owner.register('service:fetch', FetchStub);this.owner.register('service:notifications', NotificationsStub);++ // Glimmer components cannot be constructed by hand, so let Ember build one and+ // capture it: the actions below are only reachable through third-party controls+ // in the template, or not rendered at all.+ const captured = captureComponent(this.owner, 'configure/queue', ConfigureQueueComponent);+ this.build = async () => {+ await render(hbs`+ <div id="next-view-section-subheader-actions"></div>+ <Configure::Queue />+ `);+ await flush();+ return captured.instance;+ };});test('it renders the queue panel and wormholes its save button to the subheader', async function (assert) {@@ -51,4 +79,72 @@ module('Integration | Component | configure/queue', function (hooks) {assert.strictEqual(this.posted.at(-1).path, 'settings/queue-config');});++ test('it defaults to the sync driver with beanstalkd pointed at localhost', async function (assert) {+ this.getResponse = {};+ const component = await this.build();++ assert.strictEqual(component.driver, 'sync');+ assert.deepEqual(component.connections, []);+ // Read before anything writes them: a @tracked field's initializer only runs on+ // first access, so a test that assigns first never evaluates it.+ assert.strictEqual(component.testResponse, undefined, 'no connection test has run yet');+ assert.strictEqual(component.sqsQueue, null);+ assert.strictEqual(component.sqsSuffix, null);+ assert.strictEqual(component.sqsPrefix, null);+ assert.strictEqual(component.beanstalkdHost, 'localhost');+ assert.strictEqual(component.beanstalkdQueue, 'default');+ assert.false(component.isLoading);+ });++ test('loadConfigValues applies known keys and ignores unknown ones', async function (assert) {+ this.getResponse = { driver: 'sqs', sqsQueue: 'jobs', notAFieldOnThisComponent: 'ignored' };+ const component = await this.build();++ assert.strictEqual(component.driver, 'sqs');+ assert.strictEqual(component.sqsQueue, 'jobs');+ assert.strictEqual(component.notAFieldOnThisComponent, undefined, 'keys the component does not declare are dropped');+ });++ test('setDriver swaps the active driver', async function (assert) {+ const component = await this.build();++ component.setDriver('beanstalkd');++ assert.strictEqual(component.driver, 'beanstalkd');+ });++ test('save posts the sqs and beanstalkd settings and reports success', async function (assert) {+ this.getResponse = {};+ const component = await this.build();++ component.setDriver('sqs');+ component.sqsPrefix = 'https://sqs.example.com/1';+ component.sqsQueue = 'jobs';+ component.sqsSuffix = '-staging';++ component.save();+ assert.true(component.isLoading, 'the panel is busy while saving');+ await flush();++ const { path, payload } = this.posted.at(-1);+ assert.strictEqual(path, 'settings/queue-config');+ assert.strictEqual(payload.driver, 'sqs');+ assert.deepEqual(payload.sqs, { prefix: 'https://sqs.example.com/1', queue: 'jobs', suffix: '-staging' });+ assert.deepEqual(payload.beanstalkd, { host: 'localhost', queue: 'default' });+ assert.deepEqual(this.owner.lookup('service:notifications').successes, ['Queue configuration saved.']);+ assert.false(component.isLoading);+ });++ test('test posts the selected queue and keeps the response', async function (assert) {+ const component = await this.build();++ component.setDriver('beanstalkd');+ component.test();+ await flush();++ assert.deepEqual(this.posted.at(-1), { path: 'settings/test-queue-config', payload: { queue: 'beanstalkd' } });+ assert.deepEqual(component.testResponse, this.postResponse);+ assert.false(component.isLoading);+ });});diff --git a/console/tests/integration/components/configure/socket-test.js b/console/tests/integration/components/configure/socket-test.jsindex 33f8cda1..8f1873d4 100644--- a/console/tests/integration/components/configure/socket-test.js+++ b/console/tests/integration/components/configure/socket-test.js@@ -3,13 +3,37 @@ 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 ConfigureSocketComponent from '@fleetbase/console/components/configure/socket';+import { captureComponent } from '@fleetbase/console/tests/helpers/capture-component';++/**+ * The component drains its socket streams inside bare `async` IIFEs, which settled() does+ * not track. Yield the microtask queue a few times so each loop can consume its events.+ */+async function flush(times = 4) {+ for (let i = 0; i < times; i++) {+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+}++/** An async-iterable that yields the given items once and then completes. */+function stream(items = []) {+ return {+ async *[Symbol.asyncIterator]() {+ for (const item of items) {+ yield item;+ }+ },+ };+}module('Integration | Component | configure/socket', function (hooks) {setupRenderingTest(hooks);hooks.beforeEach(function () {this.posted = [];- const posted = this.posted;+ this.postResponse = { status: 'ok', message: 'connected' };+ const context = this;// The component opens `for await` loops over socket.instance().listener(...),// socket.subscribe('test').listener(...) and the channel itself. Hand back@@ -35,8 +59,8 @@ module('Integration | Component | configure/socket', function (hooks) {return Promise.resolve({});}post(path, payload) {- posted.push({ path, payload });- return Promise.resolve({ status: 'ok', message: 'connected' });+ context.posted.push({ path, payload });+ return Promise.resolve(context.postResponse);}}class NotificationsStub extends Service {@@ -48,6 +72,51 @@ module('Integration | Component | configure/socket', function (hooks) {this.owner.register('service:socket', SocketStub);this.owner.register('service:fetch', FetchStub);this.owner.register('service:notifications', NotificationsStub);++ /**+ * Replaces the socket service with streams that actually emit, and captures the+ * routeWillChange handler the component registers, so the console log and the+ * teardown path can both be driven. The router service is built in and cannot be+ * swapped via owner.register, so patch `on` on the injected instance.+ */+ this.buildWithEvents = async ({ errors = [], connects = [], subscribes = [], messages = [] } = {}) => {+ const closed = { count: 0 };+ const testChannel = Object.assign(stream(messages), {+ listener: () => stream(subscribes),+ close() {+ closed.count++;+ },+ });++ const socket = this.owner.lookup('service:socket');+ Object.defineProperty(socket, 'instance', {+ configurable: true,+ value: () => ({+ listener: (name) => (name === 'error' ? stream(errors) : stream(connects)),+ subscribe: () => testChannel,+ }),+ });++ const router = this.owner.lookup('service:router');+ let routeWillChange;+ Object.defineProperty(router, 'on', {+ configurable: true,+ value: (eventName, handler) => {+ if (eventName === 'routeWillChange') {+ routeWillChange = handler;+ }+ },+ });++ // Glimmer components cannot be constructed by hand, so let Ember build one and+ // capture it. Both patches above must be in place before it is created, since+ // the constructor immediately opens the socket streams.+ const captured = captureComponent(this.owner, 'configure/socket', ConfigureSocketComponent);+ await render(hbs`<Configure::Socket />`);+ await flush();++ return { component: captured.instance, closed, triggerRouteChange: () => routeWillChange() };+ };});test('it renders the socket connection panel', async function (assert) {@@ -62,4 +131,63 @@ module('Integration | Component | configure/socket', function (hooks) {assert.deepEqual(this.posted, [], 'nothing is posted on render');});++ test('testSocketConnection posts to the test channel and keeps the response', async function (assert) {+ const { component } = await this.buildWithEvents();++ component.testSocketConnection();+ assert.true(component.isLoading, 'the panel is busy while the test runs');+ await flush();++ assert.deepEqual(this.posted.at(-1), { path: 'settings/test-socket', payload: { channel: 'test' } });+ assert.deepEqual(component.testResponse, this.postResponse);+ assert.false(component.isLoading);+ });++ test('it logs a console entry for each kind of socket event', async function (assert) {+ const { component } = await this.buildWithEvents({+ errors: [{}],+ connects: [{}],+ subscribes: [{}],+ messages: [{ hello: 'world' }],+ });++ const entries = component.events.map((event) => ({ content: event.content, color: event.color }));++ assert.deepEqual(+ entries.filter((entry) => entry.content === 'Socket connection error!'),+ [{ content: 'Socket connection error!', color: 'red' }],+ 'connection errors are logged in red'+ );+ assert.deepEqual(+ entries.filter((entry) => entry.content === 'Socket is connected'),+ [{ content: 'Socket is connected', color: 'green' }],+ 'connections are logged in green'+ );+ assert.deepEqual(+ entries.filter((entry) => entry.content === 'Socket subscribed to test channel'),+ [{ content: 'Socket subscribed to test channel', color: 'blue' }],+ 'channel subscription is logged in blue'+ );+ assert.deepEqual(+ entries.filter((entry) => entry.content === JSON.stringify({ hello: 'world' }, undefined, 2)),+ [{ content: JSON.stringify({ hello: 'world' }, undefined, 2), color: 'green' }],+ 'channel messages are logged as formatted JSON'+ );+ assert.true(+ component.events.every((event) => typeof event.time === 'string' && event.time.length > 0),+ 'every entry is timestamped'+ );+ });++ test('leaving the route closes the channel and clears the console', async function (assert) {+ const { component, closed, triggerRouteChange } = await this.buildWithEvents({ connects: [{}] });++ assert.true(component.events.length > 0, 'precondition: the console has entries');++ triggerRouteChange();++ assert.strictEqual(closed.count, 1, 'the test channel is closed');+ assert.deepEqual(component.events, [], 'and the console is cleared');+ });});