mirror of
https://github.com/Floriansylvain/SnippetsManager.git
synced 2026-08-19 11:43:15 +02:00
Implemented Jest tests
This commit is contained in:
+2
-2
@@ -5,8 +5,8 @@ services:
|
|||||||
- .env
|
- .env
|
||||||
networks:
|
networks:
|
||||||
- back-net
|
- back-net
|
||||||
# ports:
|
ports:
|
||||||
# - 3306:3306
|
- 3307:3306
|
||||||
environment:
|
environment:
|
||||||
- "MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}"
|
- "MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}"
|
||||||
- "MYSQL_DATABASE=snippetsmanager"
|
- "MYSQL_DATABASE=snippetsmanager"
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
/** @type {import('ts-jest').JestConfigWithTsJest} */
|
||||||
|
const jestConfig = {
|
||||||
|
transform: { '\\.[jt]s?$': 'ts-jest' },
|
||||||
|
moduleNameMapper: {
|
||||||
|
'^(\\.{1,2}/.*)\\.[jt]s$': '$1',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default jestConfig
|
||||||
Generated
+703
-257
File diff suppressed because it is too large
Load Diff
+9
-3
@@ -7,8 +7,9 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
"build:dev": "tsc -w",
|
"build:dev": "tsc -w",
|
||||||
"start": "concurrently npm:build \"wait-on dist/app.js && node dist/app.js\"",
|
"start": "concurrently npm:build \"wait-on dist/index.js && node dist/index.js\"",
|
||||||
"dev": "concurrently npm:build:dev \"wait-on dist/app.js && nodemon dist/app.js\""
|
"dev": "concurrently npm:build:dev \"wait-on dist/index.js && nodemon dist/index.js\"",
|
||||||
|
"test": "jest"
|
||||||
},
|
},
|
||||||
"author": "",
|
"author": "",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
@@ -32,10 +33,15 @@
|
|||||||
"@types/cookie-parser": "^1.4.3",
|
"@types/cookie-parser": "^1.4.3",
|
||||||
"@types/cors": "^2.8.13",
|
"@types/cors": "^2.8.13",
|
||||||
"@types/express": "^4.17.16",
|
"@types/express": "^4.17.16",
|
||||||
|
"@types/jest": "^29.4.0",
|
||||||
"@types/jsonwebtoken": "^9.0.1",
|
"@types/jsonwebtoken": "^9.0.1",
|
||||||
|
"@types/supertest": "^2.0.12",
|
||||||
"install": "^0.13.0",
|
"install": "^0.13.0",
|
||||||
"jest": "^29.4.0",
|
"jest": "^29.4.1",
|
||||||
"npm": "^9.4.0",
|
"npm": "^9.4.0",
|
||||||
|
"supertest": "^6.3.3",
|
||||||
|
"ts-jest": "^29.0.5",
|
||||||
|
"ts-node": "^10.9.1",
|
||||||
"typescript": "^4.9.4"
|
"typescript": "^4.9.4"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { initServer } from '../app.js'
|
||||||
|
import request from 'supertest'
|
||||||
|
|
||||||
|
const app = initServer()
|
||||||
|
|
||||||
|
describe('GET /v1', () => {
|
||||||
|
it('returns status code 200 and api version message', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.get('/v1')
|
||||||
|
|
||||||
|
expect(res.statusCode).toEqual(200)
|
||||||
|
expect(res.body).toHaveProperty('message')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('POST /v1/login', () => {
|
||||||
|
it('returns status code 200 and set httpOnly jwt token cookie', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.post('/v1/login')
|
||||||
|
.set('Content-Type', 'application/json')
|
||||||
|
.send(JSON.stringify({
|
||||||
|
email: "a@a.com",
|
||||||
|
password: "aaaaaaaaaa"
|
||||||
|
}))
|
||||||
|
|
||||||
|
const jwtRegEx = /^jwt=.*Path=\/.*HttpOnly.*Secure.*SameSite=Strict.*$/
|
||||||
|
const jwtToken = res.get('Set-Cookie')
|
||||||
|
.filter(cookie => cookie.match(jwtRegEx))
|
||||||
|
|
||||||
|
expect(res.statusCode).toEqual(200)
|
||||||
|
expect(jwtToken).not.toBe(undefined)
|
||||||
|
})
|
||||||
|
})
|
||||||
+10
-8
@@ -6,9 +6,6 @@ import cors from 'cors'
|
|||||||
import cookieParser from 'cookie-parser'
|
import cookieParser from 'cookie-parser'
|
||||||
import { getJwtSecret } from './utils/jwt.js'
|
import { getJwtSecret } from './utils/jwt.js'
|
||||||
|
|
||||||
const app = express()
|
|
||||||
const appRouter = express.Router()
|
|
||||||
|
|
||||||
const authMiddleware: RequestHandler = (req, res, next) => {
|
const authMiddleware: RequestHandler = (req, res, next) => {
|
||||||
const token = req.cookies.jwt
|
const token = req.cookies.jwt
|
||||||
if (token == undefined) {
|
if (token == undefined) {
|
||||||
@@ -30,7 +27,7 @@ const appRouterGet: RequestHandler = (req, res) => {
|
|||||||
res.send({ code: 200, message: "SnippetsManager v1.0" })
|
res.send({ code: 200, message: "SnippetsManager v1.0" })
|
||||||
}
|
}
|
||||||
|
|
||||||
function initEnvVariables() {
|
function initEnvVariables(): void {
|
||||||
dotenv.config()
|
dotenv.config()
|
||||||
const varsToCheck = ['API_PORT', 'FRONT_ORIGIN']
|
const varsToCheck = ['API_PORT', 'FRONT_ORIGIN']
|
||||||
|
|
||||||
@@ -44,20 +41,25 @@ function initEnvVariables() {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
function startServer(): void {
|
export function initServer(): express.Express {
|
||||||
initEnvVariables()
|
initEnvVariables()
|
||||||
|
|
||||||
|
const app = express()
|
||||||
|
const appRouter = express.Router()
|
||||||
|
|
||||||
app.use(cors({ origin: process.env.FRONT_ORIGIN, credentials: true }))
|
app.use(cors({ origin: process.env.FRONT_ORIGIN, credentials: true }))
|
||||||
app.use(cookieParser())
|
app.use(cookieParser())
|
||||||
app.use(express.json())
|
app.use(express.json())
|
||||||
app.use(express.urlencoded({ extended: false }))
|
app.use(express.urlencoded({ extended: false }))
|
||||||
|
|
||||||
appRouter.get('/', authMiddleware, appRouterGet)
|
appRouter.get('/', appRouterGet)
|
||||||
|
|
||||||
appRouter.use(userRouter)
|
appRouter.use(userRouter)
|
||||||
app.use('/v1/', appRouter)
|
app.use('/v1/', appRouter)
|
||||||
|
|
||||||
app.listen(process.env.API_PORT, () => console.log(`Listening on port ${process.env.API_PORT}`))
|
return app
|
||||||
}
|
}
|
||||||
|
|
||||||
startServer()
|
export function startServer(app: express.Express): void {
|
||||||
|
app.listen(process.env.API_PORT, () => console.log(`Listening on port ${process.env.API_PORT}`))
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
import { startServer, initServer } from "./app.js"
|
||||||
|
|
||||||
|
const app = initServer()
|
||||||
|
startServer(app)
|
||||||
+31
-22
@@ -1,5 +1,5 @@
|
|||||||
import { PrismaClient, User } from '@prisma/client'
|
import { PrismaClient, User } from '@prisma/client'
|
||||||
import express from 'express'
|
import express, { RequestHandler } from 'express'
|
||||||
|
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import bcrypt from 'bcrypt'
|
import bcrypt from 'bcrypt'
|
||||||
@@ -29,6 +29,27 @@ async function isUserEmailAlreadyUsed(email: string): Promise<boolean> {
|
|||||||
return user != undefined
|
return user != undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function createUser(email: string, password: string) {
|
||||||
|
await prisma.user.create({
|
||||||
|
data: {
|
||||||
|
email: email,
|
||||||
|
password: password,
|
||||||
|
name: '',
|
||||||
|
picture_path: '',
|
||||||
|
created_at: new Date(),
|
||||||
|
updated_at: new Date()
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getUser(email: string): Promise<User | null> {
|
||||||
|
return await prisma.user.findFirst({
|
||||||
|
where: {
|
||||||
|
email: email
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
function parseLoginData(data: any): LoginData | undefined {
|
function parseLoginData(data: any): LoginData | undefined {
|
||||||
try {
|
try {
|
||||||
const loginData: LoginData = LoginValidator.parse(data)
|
const loginData: LoginData = LoginValidator.parse(data)
|
||||||
@@ -38,34 +59,28 @@ function parseLoginData(data: any): LoginData | undefined {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
userRouter.post("/login", async (req, res) => {
|
const userRouterPostLogin: RequestHandler = async (req, res) => {
|
||||||
const loginData = parseLoginData(req.body)
|
const loginData = parseLoginData(req.body)
|
||||||
if (loginData === undefined) {
|
if (loginData === undefined) {
|
||||||
res.status(400).json({ message: 'Incorrect credentials format.' })
|
res.status(400).json({ message: 'Incorrect credentials format.' })
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const user = await prisma.user.findFirst({
|
const user = await getUser(loginData.email)
|
||||||
where: {
|
|
||||||
email: loginData.email
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
if (await isUserValid(user, loginData) === false) {
|
if (await isUserValid(user, loginData) === false) {
|
||||||
res.status(400).json({ message: 'Incorrect credentials.' })
|
res.status(400).json({ message: 'Incorrect credentials.' })
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const jwtToken = jwt.sign({}, getJwtSecret(), { expiresIn: "1h" })
|
const jwtToken = jwt.sign({}, getJwtSecret(), { expiresIn: "1h" })
|
||||||
|
|
||||||
res.cookie('jwt', jwtToken, {
|
res.cookie('jwt', jwtToken, {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
secure: true,
|
secure: true,
|
||||||
sameSite: 'strict'
|
sameSite: 'strict'
|
||||||
}).json({ message: "Logged in! httpOnly cookie set." })
|
}).json({ message: "Logged in! httpOnly cookie set." })
|
||||||
})
|
}
|
||||||
|
|
||||||
userRouter.post("/register", async (req, res) => {
|
const userRouterPostRegister: RequestHandler = async (req, res) => {
|
||||||
const loginData = parseLoginData(req.body)
|
const loginData = parseLoginData(req.body)
|
||||||
if (loginData == undefined) {
|
if (loginData == undefined) {
|
||||||
res.status(400).json({ message: 'Incorrect credentials format.' })
|
res.status(400).json({ message: 'Incorrect credentials format.' })
|
||||||
@@ -79,18 +94,12 @@ userRouter.post("/register", async (req, res) => {
|
|||||||
|
|
||||||
const hashedPassword = await bcrypt.hash(loginData.password, 10)
|
const hashedPassword = await bcrypt.hash(loginData.password, 10)
|
||||||
|
|
||||||
await prisma.user.create({
|
createUser(loginData.email, hashedPassword)
|
||||||
data: {
|
|
||||||
email: loginData.email,
|
|
||||||
password: hashedPassword,
|
|
||||||
name: '',
|
|
||||||
picture_path: '',
|
|
||||||
created_at: new Date(),
|
|
||||||
updated_at: new Date()
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
res.json({ message: 'User successfully created!' })
|
res.json({ message: 'User successfully created!' })
|
||||||
})
|
}
|
||||||
|
|
||||||
|
userRouter.post("/login", userRouterPostLogin)
|
||||||
|
userRouter.post("/register", userRouterPostRegister)
|
||||||
|
|
||||||
export default userRouter
|
export default userRouter
|
||||||
|
|||||||
+3
-1
@@ -99,5 +99,7 @@
|
|||||||
/* Completeness */
|
/* Completeness */
|
||||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||||
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||||
}
|
},
|
||||||
|
"include": ["src/**/*"],
|
||||||
|
"exclude": ["src/**/*.test.ts", "node_modules"]
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user