Skip to content

Commit

Permalink
test(helpers): add base test class
Browse files Browse the repository at this point in the history
  • Loading branch information
jlenon7 committed May 11, 2024
1 parent adfd523 commit 9663fb4
Show file tree
Hide file tree
Showing 6 changed files with 88 additions and 54 deletions.
2 changes: 1 addition & 1 deletion src/helpers/queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class VanillaQueue<T = any> {
const path = Path.storage('queues.json')

return new File(path, '').setContent(
JSON.stringify({ default: [], deadletter: [] })
JSON.stringify({ default: [], deadletter: [] }, null, 2)
)
}

Expand Down
3 changes: 2 additions & 1 deletion src/models/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ export class User extends BaseModel {
return {
name: this.faker.person.firstName(),
email: this.faker.internet.email(),
password: this.faker.internet.password()
token: this.faker.string.uuid(),
password: await bcrypt.hash('12345', 10)
}
}
}
6 changes: 1 addition & 5 deletions storage/queues.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
{
"default":[],
"deadletter":[],
"user:email":[],
"user:password":[],
"user:email:password":[],
"user:confirm":[]
"deadletter":[]
}
27 changes: 9 additions & 18 deletions tests/e2e/auth.controller.test.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
import bcrypt from 'bcrypt'
import jwt from 'jsonwebtoken'
import { Uuid } from '@athenna/common'
import { User } from '#src/models/user'
import { Role } from '#src/models/role'
import { Config } from '@athenna/config'
import { SmtpServer } from '@athenna/mail'
import { Database } from '@athenna/database'
import { RoleUser } from '#src/models/roleuser'
import { Queue } from '#src/providers/facades/queue'
import { BaseHttpTest } from '@athenna/core/testing/BaseHttpTest'
import { BaseE2ETest } from '#tests/helpers/base.e2e.test'
import { Test, type Context, AfterAll, BeforeAll } from '@athenna/test'

export default class AuthControllerTest extends BaseHttpTest {
export default class AuthControllerTest extends BaseE2ETest {
@BeforeAll()
public async beforeAll() {
await SmtpServer.create({ disabledCommands: ['AUTH'] }).listen(5025)
Expand All @@ -30,7 +27,7 @@ export default class AuthControllerTest extends BaseHttpTest {

@Test()
public async shouldBeAbleToGetTheAuthenticatedUserUsingMeEndpoint({ request }: Context) {
const token = await ioc.use('authService').login('[email protected]', '12345')
const token = await this.getCustomerToken()
const response = await request.get('/api/v1/me', { headers: { authorization: token } })

response.assertStatusCode(200)
Expand All @@ -41,9 +38,7 @@ export default class AuthControllerTest extends BaseHttpTest {

@Test()
public async shouldThrowUnauthorizedExceptionIfAuthenticatedDontHaveRolesKey({ request }: Context) {
const token = jwt.sign({ user: { id: -1 } }, Config.get('auth.jwt.secret'), {
expiresIn: Config.get('auth.jwt.expiresIn')
})
const token = this.createFakeToken({ user: { id: -1 } })

const response = await request.get('/api/v1/me', { headers: { authorization: token } })

Expand All @@ -55,9 +50,7 @@ export default class AuthControllerTest extends BaseHttpTest {

@Test()
public async shouldThrowUnauthorizedExceptionIfAuthenticatedUserCannotBeFound({ request }: Context) {
const token = jwt.sign({ user: { id: -1, roles: [] } }, Config.get('auth.jwt.secret'), {
expiresIn: Config.get('auth.jwt.expiresIn')
})
const token = this.createFakeToken({ user: { id: -1, roles: [] } })

const response = await request.get('/api/v1/me', { headers: { authorization: token } })

Expand Down Expand Up @@ -136,8 +129,6 @@ export default class AuthControllerTest extends BaseHttpTest {

const queue = await Queue.queue('user:confirm')

console.log(response.response)

assert.deepEqual(await queue.length(), 1)
assert.isTrue(await User.exists({ email: '[email protected]' }))
response.assertStatusCode(201)
Expand Down Expand Up @@ -269,7 +260,7 @@ export default class AuthControllerTest extends BaseHttpTest {

@Test()
public async shouldBeAbleToConfirmUserAccount({ assert, request }: Context) {
const user = await User.factory().create({ token: Uuid.generate(), emailVerifiedAt: null })
const user = await User.factory().create({ emailVerifiedAt: null })

const response = await request.get('/api/v1/confirm/account', {
query: {
Expand Down Expand Up @@ -303,7 +294,7 @@ export default class AuthControllerTest extends BaseHttpTest {

@Test()
public async shouldBeAbleToConfirmUserEmail({ assert, request }: Context) {
const user = await User.factory().create({ token: Uuid.generate() })
const user = await User.factory().create()

const response = await request.get('/api/v1/confirm/email', {
query: {
Expand Down Expand Up @@ -338,7 +329,7 @@ export default class AuthControllerTest extends BaseHttpTest {

@Test()
public async shouldBeAbleToConfirmUserPassword({ assert, request }: Context) {
const user = await User.factory().create({ token: Uuid.generate() })
const user = await User.factory().create()

const response = await request.get('/api/v1/confirm/password', {
query: {
Expand Down Expand Up @@ -373,7 +364,7 @@ export default class AuthControllerTest extends BaseHttpTest {

@Test()
public async shouldBeAbleToConfirmUserEmailPassword({ assert, request }: Context) {
const user = await User.factory().create({ token: Uuid.generate() })
const user = await User.factory().create()

const response = await request.get('/api/v1/confirm/email/password', {
query: {
Expand Down
59 changes: 30 additions & 29 deletions tests/e2e/user.controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,19 @@ import { SmtpServer } from '@athenna/mail'
import { Database } from '@athenna/database'
import { RoleUser } from '#src/models/roleuser'
import { Queue } from '#src/providers/facades/queue'
import { BaseHttpTest } from '@athenna/core/testing/BaseHttpTest'
import { Test, type Context, AfterEach, BeforeEach } from '@athenna/test'
import { BaseE2ETest } from '#tests/helpers/base.e2e.test'
import { Test, type Context, AfterAll, BeforeAll } from '@athenna/test'

export default class UserControllerTest extends BaseHttpTest {
@BeforeEach()
public async beforeEach() {
export default class UserControllerTest extends BaseE2ETest {
@BeforeAll()
public async beforeAll() {
await SmtpServer.create({ disabledCommands: ['AUTH'] }).listen(5025)
await Database.runSeeders()
}

@AfterEach()
public async afterEach() {
@AfterAll()
public async afterAll() {
await Queue.truncate()
await User.truncate()
await Role.truncate()
await RoleUser.truncate()
Expand All @@ -26,7 +27,7 @@ export default class UserControllerTest extends BaseHttpTest {

@Test()
public async shouldBeAbleToGetAllUsers({ request }: Context) {
const token = await ioc.use('authService').login('[email protected]', '12345')
const token = await this.getAdminToken()
const response = await request.get('/api/v1/users', { headers: { authorization: token } })

response.assertStatusCode(200)
Expand Down Expand Up @@ -60,7 +61,7 @@ export default class UserControllerTest extends BaseHttpTest {

@Test()
public async shouldThrowUnauthorizedExceptionWhenTryingToGetAllUsersAsACustomer({ request }: Context) {
const token = await ioc.use('authService').login('[email protected]', '12345')
const token = await this.getCustomerToken()
const response = await request.get('/api/v1/users', { headers: { authorization: token } })

response.assertStatusCode(401)
Expand All @@ -72,7 +73,7 @@ export default class UserControllerTest extends BaseHttpTest {
@Test()
public async shouldBeAbleToGetAUserById({ request }: Context) {
const user = await User.find({ email: '[email protected]' })
const token = await ioc.use('authService').login('[email protected]', '12345')
const token = await this.getAdminToken()
const response = await request.get(`/api/v1/users/${user.id}`, { headers: { authorization: token } })

response.assertStatusCode(200)
Expand All @@ -84,7 +85,7 @@ export default class UserControllerTest extends BaseHttpTest {
@Test()
public async shouldBeAbleToGetOwnUserByIdAsACustomer({ request }: Context) {
const user = await User.find({ email: '[email protected]' })
const token = await ioc.use('authService').login('[email protected]', '12345')
const token = await this.getCustomerToken()
const response = await request.get(`/api/v1/users/${user.id}`, { headers: { authorization: token } })

response.assertStatusCode(200)
Expand Down Expand Up @@ -116,7 +117,7 @@ export default class UserControllerTest extends BaseHttpTest {
@Test()
public async shouldThrowUnauthorizedExceptionWhenTryingToGetAUserDifferentThenYoursAsACustomer({ request }: Context) {
const user = await User.find({ email: '[email protected]' })
const token = await ioc.use('authService').login('[email protected]', '12345')
const token = await this.getCustomerToken()
const response = await request.get(`/api/v1/users/${user.id}`, { headers: { authorization: token } })

response.assertStatusCode(401)
Expand All @@ -127,8 +128,8 @@ export default class UserControllerTest extends BaseHttpTest {

@Test()
public async shouldBeAbleToUpdateAUserName({ assert, request }: Context) {
const user = await User.find({ email: '[email protected]' })
const token = await ioc.use('authService').login('[email protected]', '12345')
const user = await this.createCustomer()
const token = await this.createToken(user)
const response = await request.put(`/api/v1/users/${user.id}`, {
body: { name: 'Customer Updated' },
headers: { authorization: token }
Expand All @@ -139,14 +140,14 @@ export default class UserControllerTest extends BaseHttpTest {
assert.deepEqual(user.name, 'Customer Updated')
response.assertStatusCode(200)
response.assertBodyContains({
data: { name: 'Customer Updated', email: '[email protected]' }
data: { name: 'Customer Updated' }
})
}

@Test()
public async shouldNotBeAbleToUpdateAUserEmailWithoutEmailConfirmation({ assert, request }: Context) {
const user = await User.find({ email: '[email protected]' })
const token = await ioc.use('authService').login('[email protected]', '12345')
const token = await this.getAdminToken()
const response = await request.put(`/api/v1/users/${user.id}`, {
body: { name: 'Customer Updated', email: '[email protected]' },
headers: { authorization: token }
Expand All @@ -168,7 +169,7 @@ export default class UserControllerTest extends BaseHttpTest {
@Test()
public async shouldNotBeAbleToUpdateAUserPasswordWithoutEmailConfirmation({ assert, request }: Context) {
const user = await User.find({ email: '[email protected]' })
const token = await ioc.use('authService').login('[email protected]', '12345')
const token = await this.getAdminToken()
const response = await request.put(`/api/v1/users/${user.id}`, {
body: { name: 'Customer Updated', password: '12345678', password_confirmation: '12345678' },
headers: { authorization: token }
Expand All @@ -190,7 +191,7 @@ export default class UserControllerTest extends BaseHttpTest {
@Test()
public async shouldNotBeAbleToUpdateAUserEmailAndPasswordWithoutEmailConfirmation({ assert, request }: Context) {
const user = await User.find({ email: '[email protected]' })
const token = await ioc.use('authService').login('[email protected]', '12345')
const token = await this.getAdminToken()
const response = await request.put(`/api/v1/users/${user.id}`, {
body: {
name: 'Customer Updated',
Expand All @@ -216,8 +217,8 @@ export default class UserControllerTest extends BaseHttpTest {

@Test()
public async shouldBeAbleToUpdateOwnUserByIdAsACustomer({ assert, request }: Context) {
const user = await User.find({ email: '[email protected]' })
const token = await ioc.use('authService').login('[email protected]', '12345')
const user = await this.createCustomer()
const token = await this.createToken(user)
const response = await request.put(`/api/v1/users/${user.id}`, {
body: {
name: 'Customer Updated'
Expand All @@ -230,7 +231,7 @@ export default class UserControllerTest extends BaseHttpTest {
assert.deepEqual(user.name, 'Customer Updated')
response.assertStatusCode(200)
response.assertBodyContains({
data: { name: 'Customer Updated', email: '[email protected]' }
data: { name: 'Customer Updated' }
})
}

Expand Down Expand Up @@ -259,7 +260,7 @@ export default class UserControllerTest extends BaseHttpTest {
request
}: Context) {
const user = await User.find({ email: '[email protected]' })
const token = await ioc.use('authService').login('[email protected]', '12345')
const token = await this.getCustomerToken()
const response = await request.put(`/api/v1/users/${user.id}`, {
body: { name: 'Admin Updated' },
headers: { authorization: token }
Expand All @@ -273,8 +274,8 @@ export default class UserControllerTest extends BaseHttpTest {

@Test()
public async shouldBeAbleToDeleteAUser({ assert, request }: Context) {
const user = await User.find({ email: '[email protected]' })
const token = await ioc.use('authService').login('[email protected]', '12345')
const user = await this.createCustomer()
const token = await this.getAdminToken()
const response = await request.delete(`/api/v1/users/${user.id}`, {
headers: { authorization: token }
})
Expand All @@ -287,8 +288,8 @@ export default class UserControllerTest extends BaseHttpTest {

@Test()
public async shouldBeAbleToDeleteOwnUserByIdAsACustomer({ assert, request }: Context) {
const user = await User.find({ email: '[email protected]' })
const token = await ioc.use('authService').login('[email protected]', '12345')
const user = await this.createCustomer()
const token = await this.createToken(user)
const response = await request.delete(`/api/v1/users/${user.id}`, {
headers: { authorization: token }
})
Expand Down Expand Up @@ -323,9 +324,9 @@ export default class UserControllerTest extends BaseHttpTest {
public async shouldThrowUnauthorizedExceptionWhenTryingToDeleteAnUserDifferentThenYoursAsACustomer({
request
}: Context) {
const user = await User.find({ email: '[email protected]' })
const token = await ioc.use('authService').login('[email protected]', '12345')
const response = await request.delete(`/api/v1/users/${user.id}`, {
const user = await this.createCustomer()
const token = await this.createToken(user)
const response = await request.delete('/api/v1/users/2', {
headers: { authorization: token }
})

Expand Down
45 changes: 45 additions & 0 deletions tests/helpers/base.e2e.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import jwt from 'jsonwebtoken'
import { User } from '#src/models/user'
import { Role } from '#src/models/role'
import { Config } from '@athenna/config'
import { RoleEnum } from '#src/enums/role.enum'
import { RoleUser } from '#src/models/roleuser'
import { BaseHttpTest } from '@athenna/core/testing/BaseHttpTest'

export class BaseE2ETest extends BaseHttpTest {
public async getAdminToken() {
return ioc.use('authService').login('[email protected]', '12345')
}

public async getCustomerToken() {
return ioc.use('authService').login('[email protected]', '12345')
}

public createFakeToken(data: any) {
return jwt.sign(data, Config.get('auth.jwt.secret'), {
expiresIn: Config.get('auth.jwt.expiresIn')
})
}

public async createToken(user: User) {
return ioc.use('authService').login(user.email, '12345')
}

public async createAdmin() {
const user = await User.factory().create()
const role = await Role.find({ name: RoleEnum.ADMIN })

await RoleUser.create({ userId: user.id, roleId: role.id })

return user
}

public async createCustomer() {
const user = await User.factory().create()
const role = await Role.find({ name: RoleEnum.CUSTOMER })

await RoleUser.create({ userId: user.id, roleId: role.id })

return user
}
}

0 comments on commit 9663fb4

Please sign in to comment.