From 47053c185d35def85ebd51f67b70f9e76d1d909a Mon Sep 17 00:00:00 2001 From: Michael Klein Date: Tue, 18 Oct 2022 16:07:12 +0200 Subject: [PATCH] Improve testability `env`-service --- ui/packages/consul-ui/app/services/env.js | 60 +++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/ui/packages/consul-ui/app/services/env.js b/ui/packages/consul-ui/app/services/env.js index bbd9a9c1ea..97b54c94cd 100644 --- a/ui/packages/consul-ui/app/services/env.js +++ b/ui/packages/consul-ui/app/services/env.js @@ -12,3 +12,63 @@ export default class EnvService extends Service { return env(key); } } +/** + * Stub class that can be used in testing when we want to test + * interactions with the EnvService. We can use `EnvStub.stubEnv` to setup + * an Env-Service that returns certain values we need to execute our tests. + * + * Example: + * + * ```js + * // some-test.js + * test('testing interaction with Env-service', async function(assert) { + * this.owner.register('service:env', class Stub extends EnvStub { + * . stubEnv = { + * CONSUL_ACLS_ENABLED: true + * } + * }) + * }) + * ``` + */ +export class EnvStub extends EnvService { + var(key) { + const { stubEnv } = this; + + const stubbed = stubEnv[key]; + + if (stubbed) { + return stubbed; + } else { + return super.var(...arguments); + } + } +} + +/** + * Helper function to allow stubbing out data that is accessed by the application + * based on the Env-service. You will need to call this before the env-service gets + * initialized because it overrides the env-service injection on the owner. + * + * Example: + * + * ```js + * test('test something env related', async function(assert) { + * setupTestEnv(this.owner, { + * CONSUL_ACLS_ENABLED: true + * }); + * + * // ... + * }) + * ``` + * + * @param {*} owner - the owner of the test instance (usually `this.owner`) + * @param {*} stubEnv - an object that holds the stubbed env-data + */ +export function setupTestEnv(owner, stubEnv) { + owner.register( + 'service:env', + class Stub extends EnvStub { + stubEnv = stubEnv; + } + ); +}