From 48925b1f3af7c12bee0e1ccb23051eaef62ac3fc Mon Sep 17 00:00:00 2001 From: NecroBread Date: Mon, 8 Jan 2024 12:11:41 +0200 Subject: [PATCH] update tests --- .env.test | 11 ++ docker-compose-test.yml | 7 ++ jest.config.js | 7 +- package-lock.json | 198 ++++++++++++++++++++++++++++++ package.json | 1 + src/app.ts | 2 +- src/config/db.ts | 4 +- src/config/get-config.ts | 10 +- src/features/user/user-service.ts | 2 +- src/index.ts | 2 +- src/middleware/auth-middleware.ts | 2 +- tests/article/article.test.ts | 17 ++- tests/root.test.ts | 14 +++ tests/setup-tests.ts | 3 + tests/test-utils.ts | 32 ++++- tests/user/signin.test.ts | 29 ++--- tests/user/signup.test.ts | 19 ++- 17 files changed, 310 insertions(+), 50 deletions(-) create mode 100644 .env.test create mode 100644 docker-compose-test.yml create mode 100644 tests/setup-tests.ts diff --git a/.env.test b/.env.test new file mode 100644 index 0000000..02c28e4 --- /dev/null +++ b/.env.test @@ -0,0 +1,11 @@ +NODE_ENV=development +PORT=5000 +ALLOW_ORIGIN="*" +ALLOW_METHODS="GET,PUT,POST,PATCH,DELETE,HEAD,OPTIONS" +ALLOW_HEADERS="Content-Type,Cache-Control,Expires" +JWT_SECRET=SUPERSECRET +DB_NAME="test_express_app" +DB_HOST=localhost +DB_PORT=5432 +DB_USERNAME=postgres +DB_PASSWORD=password \ No newline at end of file diff --git a/docker-compose-test.yml b/docker-compose-test.yml new file mode 100644 index 0000000..bbeff7f --- /dev/null +++ b/docker-compose-test.yml @@ -0,0 +1,7 @@ +version: "3" +services: + app: + command: + - "npm" + - "run" + - "test" diff --git a/jest.config.js b/jest.config.js index b413e10..cc6cd49 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,5 +1,6 @@ /** @type {import('ts-jest').JestConfigWithTsJest} */ module.exports = { - preset: 'ts-jest', - testEnvironment: 'node', -}; \ No newline at end of file + preset: "ts-jest", + testEnvironment: "node", + setupFiles: ["./tests/setup-tests.ts"], +}; diff --git a/package-lock.json b/package-lock.json index 923cd79..b3aa70e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -23,6 +23,7 @@ "reflect-metadata": "^0.2.1", "swagger-ui-express": "^5.0.0", "typeorm": "^0.3.19", + "typeorm-extension": "^3.2.0", "winston": "^3.11.0" }, "devDependencies": { @@ -859,6 +860,21 @@ "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, + "node_modules/@faker-js/faker": { + "version": "8.3.1", + "resolved": "https://registry.npmjs.org/@faker-js/faker/-/faker-8.3.1.tgz", + "integrity": "sha512-FdgpFxY6V6rLZE9mmIBb9hM0xpfvQOSNOLnzolzKwsE1DH+gC7lEKV1p1IbR0lAYyvYd5a4u3qWJzowUkw1bIw==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/fakerjs" + } + ], + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0", + "npm": ">=6.14.13" + } + }, "node_modules/@hapi/hoek": { "version": "9.3.0", "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz", @@ -2982,6 +2998,14 @@ "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==" }, + "node_modules/consola": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.2.3.tgz", + "integrity": "sha512-I5qxpzLv+sJhTVEoLYNcTW+bThDCPsit0vLNKShZx6rLtpilNpmmeTPaeqJb9ZE9dV3DGaeby6Vuhrw38WjeyQ==", + "engines": { + "node": "^14.18.0 || >=16.10.0" + } + }, "node_modules/console-control-strings": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", @@ -3180,6 +3204,11 @@ "node": ">= 0.8" } }, + "node_modules/destr": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.2.tgz", + "integrity": "sha512-65AlobnZMiCET00KaFFjUefxDX0khFA/E4myqZ7a6Sq1yZtR8+FVIvilVX66vF2uobSumxooYZChiRPCKNqhmg==" + }, "node_modules/destroy": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", @@ -3283,6 +3312,11 @@ "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==" }, + "node_modules/ebec": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/ebec/-/ebec-2.3.0.tgz", + "integrity": "sha512-bt+0tSL7223VU3PSVi0vtNLZ8pO1AfWolcPPMk2a/a5H+o/ZU9ky0n3A0zhrR4qzJTN61uPsGIO4ShhOukdzxA==" + }, "node_modules/ecdsa-sig-formatter": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", @@ -3854,6 +3888,14 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/flat": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/flat/-/flat-5.0.2.tgz", + "integrity": "sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==", + "bin": { + "flat": "cli.js" + } + }, "node_modules/flat-cache": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", @@ -5265,6 +5307,14 @@ "url": "https://github.com/chalk/supports-color?sponsor=1" } }, + "node_modules/jiti": { + "version": "1.21.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.0.tgz", + "integrity": "sha512-gFqAIbuKyyso/3G2qhiO2OM6shY6EPP/R0+mkDbyspxKazh8BXDC5FiFsUjlczgdNz/vfra0da2y+aHrusLG/Q==", + "bin": { + "jiti": "bin/jiti.js" + } + }, "node_modules/joi": { "version": "17.11.0", "resolved": "https://registry.npmjs.org/joi/-/joi-17.11.0.tgz", @@ -5454,6 +5504,61 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/locter": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/locter/-/locter-1.2.3.tgz", + "integrity": "sha512-ew6nK4ejX+Z4bRvF94mErI38mBxn6Gvi61HL+vEU6X06Pa8RrmwvhmPqCX7784UzdhQ0+qeyYOYp8Rd5mOvh1A==", + "dependencies": { + "destr": "^2.0.2", + "ebec": "^2.3.0", + "flat": "^5.0.2", + "glob": "^10.3.10", + "jiti": "^1.21.0" + } + }, + "node_modules/locter/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/locter/node_modules/glob": { + "version": "10.3.10", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.3.10.tgz", + "integrity": "sha512-fa46+tv1Ak0UPK1TOy/pZrIybNNt4HCv7SDzwyfiOZkvZLEbjsZkJBPtDHVshZjbecAoAGSC20MjLDG/qr679g==", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^2.3.5", + "minimatch": "^9.0.1", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0", + "path-scurry": "^1.10.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/locter/node_modules/minimatch": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.3.tgz", + "integrity": "sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg==", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/lodash.includes": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", @@ -5522,6 +5627,19 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" }, + "node_modules/lower-case": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/lower-case/-/lower-case-2.0.2.tgz", + "integrity": "sha512-7fm3l3NAF9WfN6W3JOmf5drwpVqX78JtoGJ3A6W0a6ZnldM41w2fV5D490psKFTpMds8TJse/eHLFFsNHHjHgg==", + "dependencies": { + "tslib": "^2.0.3" + } + }, + "node_modules/lower-case/node_modules/tslib": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz", + "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==" + }, "node_modules/lru-cache": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", @@ -5849,6 +5967,20 @@ "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==" }, + "node_modules/no-case": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/no-case/-/no-case-3.0.4.tgz", + "integrity": "sha512-fgAN3jGAh+RoxUGZHTSOLJIqUc2wmoBwGR4tbpNAKmmovFoWq0OdRkb0VkldReO2a2iBT/OEulG9XSUc10r3zg==", + "dependencies": { + "lower-case": "^2.0.2", + "tslib": "^2.0.3" + } + }, + "node_modules/no-case/node_modules/tslib": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz", + "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==" + }, "node_modules/node-addon-api": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-5.1.0.tgz", @@ -6185,6 +6317,20 @@ "node": ">= 0.8" } }, + "node_modules/pascal-case": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/pascal-case/-/pascal-case-3.1.2.tgz", + "integrity": "sha512-uWlGT3YSnK9x3BQJaOdcZwrnV6hPpd8jFH1/ucpiLRPh/2zCVJKS19E4GvYHvaCcACn3foXZ0cLB9Wrx1KGe5g==", + "dependencies": { + "no-case": "^3.0.4", + "tslib": "^2.0.3" + } + }, + "node_modules/pascal-case/node_modules/tslib": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz", + "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==" + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -6595,6 +6741,23 @@ "node": ">= 0.6" } }, + "node_modules/rapiq": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/rapiq/-/rapiq-0.9.0.tgz", + "integrity": "sha512-k4oT4RarFBrlLMJ49xUTeQpa/us0uU4I70D/UEnK3FWQ4GENzei01rEQAmvPKAIzACo4NMW+YcYJ7EVfSa7EFg==", + "dependencies": { + "ebec": "^1.1.0", + "smob": "^1.4.0" + } + }, + "node_modules/rapiq/node_modules/ebec": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ebec/-/ebec-1.1.1.tgz", + "integrity": "sha512-JZ1vcvPQtR+8LGbZmbjG21IxLQq/v47iheJqn2F6yB2CgnGfn8ZVg3myHrf3buIZS8UCwQK0jOSIb3oHX7aH8g==", + "dependencies": { + "smob": "^1.4.0" + } + }, "node_modules/raw-body": { "version": "2.5.1", "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz", @@ -7018,6 +7181,11 @@ "npm": ">= 3.0.0" } }, + "node_modules/smob": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/smob/-/smob-1.4.1.tgz", + "integrity": "sha512-9LK+E7Hv5R9u4g4C3p+jjLstaLe11MDsL21UpYaCNmapvMkYhqCV4A/f/3gyH8QjMyh6l68q9xC85vihY9ahMQ==" + }, "node_modules/socks": { "version": "2.7.1", "resolved": "https://registry.npmjs.org/socks/-/socks-2.7.1.tgz", @@ -7795,6 +7963,36 @@ } } }, + "node_modules/typeorm-extension": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/typeorm-extension/-/typeorm-extension-3.2.0.tgz", + "integrity": "sha512-96mVEUiT78+n2jceTKUZ4WF1EYaii9ZnilI0FbOifoT0jUAOrNvQ1pfiCRfu3z2AlVg6l0wOr/n+MSlyCm3ALA==", + "dependencies": { + "@faker-js/faker": "^8.3.1", + "consola": "^3.2.3", + "locter": "^1.2.3", + "pascal-case": "^3.1.2", + "rapiq": "^0.9.0", + "reflect-metadata": "^0.1.13", + "smob": "^1.4.1", + "yargs": "^17.7.2" + }, + "bin": { + "typeorm-extension": "bin/cli.cjs", + "typeorm-extension-esm": "bin/cli.mjs" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "typeorm": "~0.3.0" + } + }, + "node_modules/typeorm-extension/node_modules/reflect-metadata": { + "version": "0.1.14", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.14.tgz", + "integrity": "sha512-ZhYeb6nRaXCfhnndflDK8qI6ZQ/YcWZCISRAWICW9XYqMUwjZM9Z0DveWX/ABN01oxSHwVxKQmxeYZSsm0jh5A==" + }, "node_modules/typeorm/node_modules/brace-expansion": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", diff --git a/package.json b/package.json index c4ae3f4..1f6a683 100644 --- a/package.json +++ b/package.json @@ -38,6 +38,7 @@ "reflect-metadata": "^0.2.1", "swagger-ui-express": "^5.0.0", "typeorm": "^0.3.19", + "typeorm-extension": "^3.2.0", "winston": "^3.11.0" }, "devDependencies": { diff --git a/src/app.ts b/src/app.ts index 72bbde3..f49c1f5 100644 --- a/src/app.ts +++ b/src/app.ts @@ -5,7 +5,7 @@ import router from "./router"; import path from "path"; import handleErrors from "./middleware/error-middleware"; import loggerMiddleware from "./middleware/logger-middleware"; -import getConfig from "./config/get-config"; +import { getConfig } from "./config/get-config"; import * as swaggerDoc from "./swagger.json"; import swagger from "swagger-ui-express"; import helmet from "helmet"; diff --git a/src/config/db.ts b/src/config/db.ts index 2f66a66..2947df2 100644 --- a/src/config/db.ts +++ b/src/config/db.ts @@ -3,7 +3,7 @@ import "reflect-metadata"; import { Article } from "../features/article/article-entity"; import { Comment } from "../features/comment/comment-entity"; import { User } from "../features/user/user-entity"; -import getConfig from "./get-config"; +import { getConfig } from "./get-config"; const config = getConfig(); @@ -13,7 +13,7 @@ export const AppDataSource = new DataSource({ port: parseInt(config.DB_PORT), username: config.DB_USERNAME, password: config.DB_PASSWORD, - database: "express_app", + database: config.DB_NAME, synchronize: config.NODE_ENV === "production" ? false : true, logging: true, entities: [Article, Comment, User], diff --git a/src/config/get-config.ts b/src/config/get-config.ts index 2807b39..de961ac 100644 --- a/src/config/get-config.ts +++ b/src/config/get-config.ts @@ -3,11 +3,12 @@ import dotenv from "dotenv"; /** * Load enviroment variables */ -dotenv.config(); -dotenv.config({ path: `.env.local`, override: true }); +if (!process.env.NODE_ENV) { + dotenv.config(); + dotenv.config({ path: `.env.local`, override: true }); +} -export default function getConfig() { - console.log(process.env); +export function getConfig() { return { NODE_ENV: process.env.NODE_ENV, PORT: process.env.PORT, @@ -15,6 +16,7 @@ export default function getConfig() { ALLOW_METHODS: process.env.ALLOW_METHODS, ALLOW_HEADERS: process.env.ALLOW_HEADERS, JWT_SECRET: process.env.JWT_SECRET, + DB_NAME: process.env.DB_NAME, DB_HOST: process.env.DB_HOST, DB_PORT: process.env.DB_PORT, DB_PASSWORD: process.env.DB_PASSWORD, diff --git a/src/features/user/user-service.ts b/src/features/user/user-service.ts index 0ea8c2e..c40e206 100644 --- a/src/features/user/user-service.ts +++ b/src/features/user/user-service.ts @@ -1,5 +1,5 @@ import jwt from "jsonwebtoken"; -import getConfig from "../../config/get-config"; +import { getConfig } from "../../config/get-config"; import { IUserLocal, ISignUpUserData, UserDto, IUpdateUserData } from "./user-types"; import { BadRequestError, InternalServerError, NotFoundError, UnauthorizedError } from "../../utils/app-error"; import { User } from "./user-entity"; diff --git a/src/index.ts b/src/index.ts index adeb369..7ad751e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,6 @@ import app from "./app"; import { AppDataSource } from "./config/db"; -import getConfig from "./config/get-config"; +import { getConfig } from "./config/get-config"; import { AppError } from "./utils/app-error"; const config = getConfig(); diff --git a/src/middleware/auth-middleware.ts b/src/middleware/auth-middleware.ts index 1534f63..e0eccd1 100644 --- a/src/middleware/auth-middleware.ts +++ b/src/middleware/auth-middleware.ts @@ -1,7 +1,7 @@ import jwt from "jsonwebtoken"; import { Request, Response, NextFunction } from "express"; import { InternalServerError, UnauthorizedError } from "../utils/app-error"; -import getConfig from "../config/get-config"; +import { getConfig } from "../config/get-config"; import { IUserLocal } from "../features/user/user-types"; const authenticateTokenMiddleware = () => (req: Request, res: Response, next: NextFunction) => { diff --git a/tests/article/article.test.ts b/tests/article/article.test.ts index 304c440..42e0197 100644 --- a/tests/article/article.test.ts +++ b/tests/article/article.test.ts @@ -1,7 +1,7 @@ import supertest, { SuperTest, Test } from "supertest"; import app from "../../src/app"; -import mongoose from "mongoose"; -import { testConnectionString } from "../test-utils"; +import { initTestDataSource } from "../test-utils"; +import { DataSource } from "typeorm"; const url = "/api/v1/articles"; const mockUser = { @@ -11,6 +11,8 @@ const mockUser = { password: "123123", }; +let db: DataSource; + describe(`${url}`, () => { let agent: SuperTest; @@ -24,19 +26,16 @@ describe(`${url}`, () => { beforeAll(async () => { require("dotenv").config(); - await mongoose.connect(testConnectionString); + db = await initTestDataSource(); agent = supertest(app); - await agent - .post("/api/v1/user/signup") - .set("Content-Type", "application/json") - .send(mockUser); + await agent.post("/api/v1/user/signup").set("Content-Type", "application/json").send(mockUser); }); afterAll((done) => { - mongoose.connection.dropDatabase().then(() => { - mongoose.connection.close(); + db.dropDatabase().then(() => { + db.destroy(); done(); }); }); diff --git a/tests/root.test.ts b/tests/root.test.ts index d7706a5..9347ee4 100644 --- a/tests/root.test.ts +++ b/tests/root.test.ts @@ -1,7 +1,21 @@ import supertest from "supertest"; import app from "../src/app"; +import { initTestDataSource } from "./test-utils"; +import { DataSource } from "typeorm"; + +let db: DataSource; describe("root", () => { + beforeAll(async () => { + db = await initTestDataSource(); + }); + + afterAll((done) => { + db.dropDatabase().then(() => { + db.destroy(); + done(); + }); + }); test("should return 404 and a message when url does not exist", async () => { const test = await supertest(app).get("/asdasdc1").expect(404); diff --git a/tests/setup-tests.ts b/tests/setup-tests.ts new file mode 100644 index 0000000..8eb996b --- /dev/null +++ b/tests/setup-tests.ts @@ -0,0 +1,3 @@ +import * as dotenv from "dotenv"; + +dotenv.config({ path: `.env.test`, override: true }); diff --git a/tests/test-utils.ts b/tests/test-utils.ts index 82c7f2b..74c2f09 100644 --- a/tests/test-utils.ts +++ b/tests/test-utils.ts @@ -1,2 +1,30 @@ -export const testConnectionString = - "mongodb://localhost:27017/express-template-test"; +import { DataSource, DataSourceOptions } from "typeorm"; +import { Article } from "../src/features/article/article-entity"; +import { Comment } from "../src/features/comment/comment-entity"; +import { User } from "../src/features/user/user-entity"; +import { createDatabase } from "typeorm-extension"; +import { AppDataSource } from "../src/config/db"; +import { getConfig } from "../src/config/get-config"; + +export async function initTestDataSource(): Promise { + const config = getConfig(); + + const options: DataSourceOptions = { + type: "postgres", + host: config.DB_HOST, + port: 5000, + username: config.DB_USERNAME, + password: config.DB_PASSWORD, + database: config.DB_NAME, + synchronize: config.NODE_ENV === "production" ? false : true, + logging: true, + entities: [Article, Comment, User], + }; + + await createDatabase({ + options, + ifNotExist: true, + }); + + return AppDataSource.initialize(); +} diff --git a/tests/user/signin.test.ts b/tests/user/signin.test.ts index de84d7d..225bf5d 100644 --- a/tests/user/signin.test.ts +++ b/tests/user/signin.test.ts @@ -1,33 +1,30 @@ import supertest, { SuperTest, Test } from "supertest"; import app from "../../src/app"; -import mongoose from "mongoose"; -import { testConnectionString } from "../test-utils"; +import { DataSource } from "typeorm"; +import { initTestDataSource } from "../test-utils"; const url = "/api/v1/user/signin"; +let db: DataSource; describe(`${url}`, () => { let agent: SuperTest; beforeAll(async () => { - require("dotenv").config(); + db = await initTestDataSource(); agent = supertest(app); - return mongoose.connect(testConnectionString).then(async () => { - // signup a user - return await agent - .post("/api/v1/user/signup") - .set("Content-Type", "application/json") - .send({ - username: "user", - firstName: "User", - lastName: "Useroff", - password: "123123", - }); + // signup a user + return await agent.post("/api/v1/user/signup").set("Content-Type", "application/json").send({ + username: "user", + firstName: "User", + lastName: "Useroff", + password: "123123", }); }); + afterAll((done) => { - mongoose.connection.dropDatabase().then(() => { - mongoose.connection.close(); + db.dropDatabase().then(() => { + db.destroy(); done(); }); }); diff --git a/tests/user/signup.test.ts b/tests/user/signup.test.ts index 9376517..e4f73d8 100644 --- a/tests/user/signup.test.ts +++ b/tests/user/signup.test.ts @@ -1,23 +1,24 @@ -import mongoose from "mongoose"; import supertest, { SuperTest, Test } from "supertest"; import app from "../../src/app"; -import { testConnectionString } from "../test-utils"; +import { DataSource } from "typeorm"; +import { initTestDataSource } from "../test-utils"; +import { User } from "../../src/features/user/user-entity"; +import * as config from "../../src/config/get-config"; const url = "/api/v1/user/signup"; +let db: DataSource; describe(`${url}`, () => { let agent: SuperTest; beforeAll(async () => { - require("dotenv").config(); + db = await initTestDataSource(); agent = supertest(app); - - await mongoose.connect(testConnectionString); }); afterAll((done) => { - mongoose.connection.dropDatabase().then(() => { - mongoose.connection.close(); + db.dropDatabase().then(() => { + db.destroy(); done(); }); }); @@ -76,9 +77,7 @@ describe(`${url}`, () => { }) .expect(400); - expect(test.body.message).toBe( - '"username" must only contain alpha-numeric characters' - ); + expect(test.body.message).toBe('"username" must only contain alpha-numeric characters'); expect(test.body.data).toBe(null); expect(test.body.code).toBe(400); });