Skip to content

Commit

Permalink
fixed tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ZenithGD committed Jan 31, 2025
1 parent 8871dae commit a322f99
Show file tree
Hide file tree
Showing 10 changed files with 123 additions and 48 deletions.
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
PORT=...
API_URL=...
SECRET_KEY=SECRET
TURSO_DATABASE_URL=...
TURSO_AUTH_TOKEN=...
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,5 @@ dist
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

!.env.example
3 changes: 3 additions & 0 deletions api/controllers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const COOKIE_OPTIONS = {

export async function signUp (req, res, next) {
const { email, password } = req.body
console.log('Email =', email, 'Password =', password)

const salt = randomBytes(16).toString('hex')
const hash = pbkdf2Sync(password, salt, HASH_CONFIG.iterations, HASH_CONFIG.keyLength, HASH_CONFIG.digest).toString('hex')
Expand All @@ -37,6 +38,8 @@ export async function signUp (req, res, next) {
export async function signIn (req, res, next) {
const { email, password } = req.body

console.log('signin data:', email, password)

const [user] = await db
.select({ id: users.id, salt: users.salt, password: users.password })
.from(users)
Expand Down
3 changes: 2 additions & 1 deletion api/middlewares/validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ export const validateRequest = (schemas) => (req, res, next) => {
for (const key of ['body', 'params', 'query', 'headers']) {
if (schemas[key] && req[key]) {
const result = schemas[key].safeParse(req[key])
console.log(result)
if (!result.success) {
const error = result.error.errors[0]
console.log(error.message)
console.log('error on validation', error.message)
return next(new BadRequest({ message: `${error.path[0]} ${error.message.toLowerCase()}` }))
}
}
Expand Down
30 changes: 15 additions & 15 deletions test/auth/signIn.test.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,36 @@
import { BadRequest, NotFound, Unauthorized } from '#api/lib/http.js'
import { db } from '#db/index.js'
import { users } from '#db/schemas/users.js'
import { invalidCredentials, invalidParams, nonExistentUser, validUser } from '#test/mocks/users/index.js'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { signInValues } from '#test/mocks/users/index.js'
import { afterAll, beforeAll, describe, expect, test } from 'vitest'
import { cleanUsers } from '../utils'

describe('Authentication tests for /auth/sign-in', () => {
describe.sequential('Authentication tests for /auth/sign-in', () => {
beforeAll(async () => {
await fetch(`${process.env.API_URL}/auth/sign-up`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(validUser)
body: JSON.stringify(signInValues.validUser)
})
})

// Here, we clean only the users that this suite uses/creates
afterAll(async () => {
await db.delete(users)
await cleanUsers(signInValues)
})

it('Should log in successfully with valid credentials', async () => {
test('Should log in successfully with valid credentials', async () => {
const response = await fetch(`${process.env.API_URL}/auth/sign-in`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(validUser)
body: JSON.stringify(signInValues.validUser)
})
expect(response.status).toBe(200)
})

it('Should return 400 for missing or invalid data', async () => {
test('Should return 400 for missing or invalid data', async () => {
const response = await fetch(`${process.env.API_URL}/auth/sign-in`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(invalidParams)
body: JSON.stringify(signInValues.invalidParams)
})
const { status } = await response.json()

Expand All @@ -40,11 +40,11 @@ describe('Authentication tests for /auth/sign-in', () => {
expect(status.error_message).toBe('password required')
})

it('Should return 401 for incorrect credentials', async () => {
test('Should return 401 for incorrect credentials', async () => {
const response = await fetch(`${process.env.API_URL}/auth/sign-in`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(invalidCredentials)
body: JSON.stringify(signInValues.invalidCredentials)
})
const { status } = await response.json()

Expand All @@ -54,11 +54,11 @@ describe('Authentication tests for /auth/sign-in', () => {
expect(status.error_message).toBe(unauthorized.message)
})

it('Should return 404 if user does not exist', async () => {
test('Should return 404 if user does not exist', async () => {
const response = await fetch(`${process.env.API_URL}/auth/sign-in`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(nonExistentUser)
body: JSON.stringify(signInValues.nonExistentUser)
})
const { status } = await response.json()

Expand Down
14 changes: 7 additions & 7 deletions test/auth/signOut.test.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
import { Unauthorized } from '#api/lib/http.js'
import { db } from '#db/index.js'
import { users } from '#db/schemas/users.js'
import { validUser } from '#test/mocks/users/index.js'
import { signOutValues } from '#test/mocks/users/index.js'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { cleanUsers } from '../utils'

async function loginAndGetToken () {
await fetch(`${process.env.API_URL}/auth/sign-up`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(validUser)
body: JSON.stringify(signOutValues.validUser)
})
const { data } = await fetch(`${process.env.API_URL}/auth/sign-in`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(validUser)
body: JSON.stringify(signOutValues.validUser)
}).then(res => res.json())
return data.token
}

describe('User logout tests for /auth/sign-out', () => {
describe.sequential('User logout tests for /auth/sign-out', () => {
let token = null

beforeAll(async () => {
token = await loginAndGetToken()
})

// Here, we clean only the users that this suite uses/creates
afterAll(async () => {
await db.delete(users)
await cleanUsers(signOutValues)
})

it('Should log out successfully with a valid session', async () => {
Expand Down
18 changes: 12 additions & 6 deletions test/auth/signUp.test.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import { BadRequest, Conflict } from '#api/lib/http.js'
import { invalidUser, validUser } from '#test/mocks/users/index.js'
import { describe, expect, it } from 'vitest'
import { signUpValues } from '#test/mocks/users/index.js'
import { afterAll, describe, expect, it } from 'vitest'
import { cleanUsers } from '../utils'

describe.sequential('User registration tests for /auth/sign-up', () => {
// Here, we clean only the users that this suite uses/creates
afterAll(async () => {
await cleanUsers(signUpValues)
})

describe('User registration tests for /auth/sign-up', () => {
it('Should create a new user successfully', async () => {
const response = await fetch(`${process.env.API_URL}/auth/sign-up`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(validUser)
body: JSON.stringify(signUpValues.validUser)
})
expect(response.status).toBe(201)
})
Expand All @@ -16,7 +22,7 @@ describe('User registration tests for /auth/sign-up', () => {
const response = await fetch(`${process.env.API_URL}/auth/sign-up`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(validUser)
body: JSON.stringify(signUpValues.validUser)
})
const { status } = await response.json()

Expand All @@ -30,7 +36,7 @@ describe('User registration tests for /auth/sign-up', () => {
const response = await fetch(`${process.env.API_URL}/auth/sign-up`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(invalidUser)
body: JSON.stringify(signUpValues.invalidUser)
})
const { status } = await response.json()

Expand Down
38 changes: 29 additions & 9 deletions test/mocks/users/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,33 @@
export const validUser = {
email: '[email protected]',
password: '12345678'
export const signUpValues = {
validUser: {
email: '[email protected]',
password: '12345678'
},
invalidUser: {
email: '',
password: ''
}
}

export const invalidUser = {
email: '',
password: ''
export const signInValues = {
validUser: {
email: '[email protected]',
password: '12345678'
},
invalidParams: {
email: '[email protected]'
},
invalidCredentials: {
email: '[email protected]', password: 'wrongpassword'
},
nonExistentUser: {
email: '[email protected]', password: 'randompass'
}
}

export const invalidParams = { email: '[email protected]' }
export const invalidCredentials = { email: '[email protected]', password: 'wrongpassword' }
export const nonExistentUser = { email: '[email protected]', password: 'randompass' }
export const signOutValues = {
validUser: {
email: '[email protected]',
password: '12345678'
}
}
23 changes: 13 additions & 10 deletions test/setup.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { db } from '#db/index.js'
import { users } from '#db/schemas/users.js'
import { afterAll, beforeAll } from 'vitest'
// Add your setup.js logic here! You can use the beforeAll and afterAll hooks to run
// something before/after **a describe block** runs.

beforeAll(async () => {
await db.delete(users)
})

afterAll(async () => {
await db.delete(users)
})
/**
* Notes:
*
* - Using beforeAll and afterAll might be tricky here if you want to do something
* to the global state of your application. Ensure you don't wipe out your whole
* database here!
*
* - If you want to remove data and multiple describe tests depend on them,
* consider adding individual beforeAll and afterAll tests on each describe block!
* See the test suites for an example.
*/
35 changes: 35 additions & 0 deletions test/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { db } from '#db/index.js'
import { users } from '#db/schemas/users.js'
import { inArray } from 'drizzle-orm'
/**
* Remove users given by object. Each key should contain an
* object with information about an user. See 'mocks/users.js' for
* an example of an object
*
* @param {users} userData the user data. Must contain at least the email
* to uniquely identify users.
*/
export async function cleanUsers (userData) {
// extract all distinct emails
const emails = Object.values(userData)
.map((entry) => entry.email)
.filter((email, index, self) => email && self.indexOf(email) === index)

if (emails.length === 0) {
return
}

// try to delete all the emails from the user object
try {
const result = await db
.delete(users)
.where(inArray(users.email, emails))
.returning({ email: users.email })

console.log('Deleted users:', result)

return result
} catch (error) {
console.error('Error deleting users:', error)
}
}

0 comments on commit a322f99

Please sign in to comment.