From 4309b4e25ca1fcaf40fe76726c32e94c32769608 Mon Sep 17 00:00:00 2001 From: markpit Date: Fri, 22 Nov 2024 13:34:11 +0000 Subject: [PATCH] Example of better way to manage flags and mocks --- src/controllers/start.controller.ts | 7 +++++++ src/test/flag.test.ts | 19 +++++++++++++++++++ src/test/global.setup.ts | 4 ++++ src/utils/feature.flag.ts | 12 ++++++++++++ 4 files changed, 42 insertions(+) create mode 100644 src/test/flag.test.ts create mode 100644 src/utils/feature.flag.ts diff --git a/src/controllers/start.controller.ts b/src/controllers/start.controller.ts index 49c66d9..e72fc21 100644 --- a/src/controllers/start.controller.ts +++ b/src/controllers/start.controller.ts @@ -1,11 +1,18 @@ import { NextFunction, Request, Response } from "express"; import * as config from "../config"; +import { hasFeature } from "utils/feature.flag"; export const get = (_req: Request, res: Response, _next: NextFunction) => { // example error message using the locales json files const errorMessage = res.locals.i18n["startPage"]["errorStartAddressMissing"]; + if (hasFeature().FLAG_1) { + console.log("***** FLAG_1"); + } + if (hasFeature().FLAG_2) { + console.log("***** FLAG_2"); + } return res.render(config.START_TEMPLATE, { errorMessage }); diff --git a/src/test/flag.test.ts b/src/test/flag.test.ts new file mode 100644 index 0000000..143e88f --- /dev/null +++ b/src/test/flag.test.ts @@ -0,0 +1,19 @@ +import app from "app"; +import request from "supertest"; +import * as config from "../config"; +import { hasFeature } from "../utils/feature.flag"; + +jest.mock("../utils/feature.flag"); + +(hasFeature as jest.Mock).mockReturnValue({ + "FLAG_1": false, + "FLAG_2": true +}); + +describe("Experimental flags test", () => { + test("something", async () => { + await request(app).get(config.START_URL); + + // check console to see what is logged + }); +}); diff --git a/src/test/global.setup.ts b/src/test/global.setup.ts index fcb4ac8..fc2416e 100644 --- a/src/test/global.setup.ts +++ b/src/test/global.setup.ts @@ -17,4 +17,8 @@ export default () => { process.env.PIWIK_SITE_ID = "24"; process.env.PIWIK_URL = "piwik.url"; process.env.PORT = "3000"; + + process.env.FLAG_1 = "false"; + process.env.FLAG_2 = "false"; + }; diff --git a/src/utils/feature.flag.ts b/src/utils/feature.flag.ts new file mode 100644 index 0000000..41f146d --- /dev/null +++ b/src/utils/feature.flag.ts @@ -0,0 +1,12 @@ +import { getEnvironmentValueAsBoolean } from "./environment.value"; + +type FeatureFlags = { + [key: string]: boolean +} + +const flags: FeatureFlags = { + "FLAG_1": getEnvironmentValueAsBoolean("FLAG_1"), + "FLAG_2": getEnvironmentValueAsBoolean("FLAG_2") +}; + +export const hasFeature = (): FeatureFlags => flags;