Skip to content

Commit

Permalink
test env.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
cyri113 committed May 20, 2023
1 parent d3982da commit be88aed
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 9 deletions.
41 changes: 41 additions & 0 deletions __test__/config/env.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/* eslint-disable @typescript-eslint/no-var-requires */
describe("env", () => {
describe("schema", () => {
it("should validate the schema successfully", () => {
expect.assertions(1);
expect(() => {
import("../../src/config/env");
}).not.toThrowError();
});
});

describe("environment variables", () => {
const DEFAULT_ENV = process.env;

beforeEach(() => {
jest.resetModules();
process.env = { ...DEFAULT_ENV };
});

afterAll(() => {
process.env = DEFAULT_ENV;
});

it("should throw an error if required environment variables are missing", () => {
expect.assertions(1);
delete process.env.MONGODB_HOST;
const expectedErrorMessage =
'Config validation error: "MONGODB_HOST" is required';
expect(() => {
require("../../src/config/env");
}).toThrowError(expectedErrorMessage);
});

it("should configure MONGODB_URL", () => {
expect.assertions(1);
process.env.MONGODB_NAME = "db";
const { env } = require("../../src/config/env");
expect(env.MONGODB_URL).toEqual("mongodb://root:pass@localhost:27017/db");
});
});
});
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"build": "npx tsc",
"start": "node dist/index.js",
"dev": "env-cmd nodemon ./src/index.ts",
"test": "env-cmd jest",
"test": "env-cmd jest --coverage",
"prettier": "npx prettier --write .",
"lint": "npx eslint ."
},
Expand Down
14 changes: 7 additions & 7 deletions src/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,21 @@ const schema = Joi.object()
})
.unknown();

const { value: env, error } = schema
const { value, error } = schema
.prefs({ errors: { label: "key" } })
.validate(process.env);

if (error != null) {
throw new Error(`Config validation error: ${error.message}`);
}

const MONGODB_URL = `mongodb://${env.MONGODB_USER}:${env.MONGODB_PASS}@${
env.MONGODB_HOST
}:${env.MONGODB_PORT}/${
env.MONGODB_NAME !== undefined ? env.MONGODB_NAME : ""
const MONGODB_URL = `mongodb://${value.MONGODB_USER}:${value.MONGODB_PASS}@${
value.MONGODB_HOST
}:${value.MONGODB_PORT}/${
value.MONGODB_NAME !== undefined ? value.MONGODB_NAME : ""
}`;

export default {
...env,
export const env = {
...value,
MONGODB_URL,
};
2 changes: 1 addition & 1 deletion src/config/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import env from "./env";
import { env } from "./env";

export { env };

0 comments on commit be88aed

Please sign in to comment.