-
Notifications
You must be signed in to change notification settings - Fork 12
feat:add e2e testing initial setup #17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
5516673
feat:add e2e testing initial setup
MasterBrian99 a6c39cc
feat: add e2e testing to workflow
MasterBrian99 de65772
feat: add postgres container intiialization setup seperately
MasterBrian99 c627d5f
fix: extend timeout for app initialization and teardown in e2e tests
MasterBrian99 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| import { StartedPostgreSqlContainer } from '@testcontainers/postgresql'; | ||
|
|
||
| declare global { | ||
| // eslint-disable-next-line no-var | ||
| var __TEST__: boolean; | ||
| // eslint-disable-next-line no-var | ||
| var __Container__: { | ||
| postgres: StartedPostgreSqlContainer | null; | ||
| }; | ||
| } | ||
|
|
||
| export {}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| import { Test, TestingModule } from '@nestjs/testing'; | ||
| import { ConfigModule, ConfigService } from '@nestjs/config'; | ||
| import { createTestConfig } from '../helpers/test-configuration'; | ||
| import { TestAppModule } from '../test-app.module'; | ||
| export class TestModuleFactory { | ||
| static async createTestModule(dbUrl: string): Promise<TestingModule> { | ||
| const databaseUrl = dbUrl + '?sslmode=disable'; | ||
| // this is to ignore warning from env not found error. does not matter what we put | ||
| process.env.DATABASE_URL = databaseUrl; | ||
| process.env.SECRET = 'fqipdmzavlbb9cvbzpab2fw5h5j4tu'; | ||
| const testConfig = createTestConfig(databaseUrl); | ||
| const moduleRef = await Test.createTestingModule({ | ||
| imports: [ | ||
| ConfigModule.forRoot({ | ||
| load: [() => testConfig], | ||
| isGlobal: true, | ||
| }), | ||
| TestAppModule, | ||
| ], | ||
| }) | ||
| .overrideProvider(ConfigService) | ||
| .useValue({ | ||
| get: (key: string) => { | ||
| const keys = key.split('.'); | ||
| let value = testConfig; | ||
| for (const k of keys) { | ||
| value = value[k]; | ||
| } | ||
| return value; | ||
| }, | ||
| }) | ||
| .compile(); | ||
|
|
||
| return moduleRef; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| // test/config/test-configuration.ts | ||
| import { AppConfig, LoggerFormat } from '../../src/config/configuration'; | ||
|
|
||
| export const createTestConfig = (databaseUrl: string): AppConfig => ({ | ||
| corsMaxAge: 86400, | ||
| database: { | ||
| poolSize: 5, | ||
| url: databaseUrl, | ||
| }, | ||
| port: 3000, | ||
| secret: 'kugk2iz30q5mlc6056der8sdnadibb', | ||
| logger: { | ||
| format: LoggerFormat.Json, | ||
| level: 'error', | ||
| }, | ||
| isDevEnv: false, | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,9 +1,17 @@ | ||
| { | ||
| "moduleFileExtensions": ["js", "json", "ts"], | ||
| "rootDir": ".", | ||
| "rootDir": "./", | ||
| "moduleNameMapper": { | ||
| "^src/(.*)$": "<rootDir>/src/$1" | ||
| }, | ||
| "modulePaths": ["<rootDir>"], | ||
| "moduleDirectories": ["<rootDir>/", "node_modules", "src", "<rootDir>/../"], | ||
| "testEnvironment": "node", | ||
| "testRegex": ".e2e-spec.ts$", | ||
| "transform": { | ||
| "^.+\\.(t|j)s$": "ts-jest" | ||
| } | ||
| }, | ||
| "globalSetup": "./setup/global-setup.ts", | ||
| "globalTeardown": "./setup/global-teardown.ts", | ||
| "setupFilesAfterEnv": ["<rootDir>/@types/globals.d.ts"] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| import { CanActivate, ExecutionContext } from '@nestjs/common'; | ||
| import MOCK_USERS from './user-mocks'; | ||
|
|
||
| export class MockJwtGuard implements CanActivate { | ||
| canActivate(context: ExecutionContext): boolean { | ||
| const req = context.switchToHttp().getRequest(); | ||
| // Attach a mock user to the request for testing | ||
| req.user = { ...MOCK_USERS.user1 }; | ||
| return true; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| const MOCK_USERS = { | ||
| user1: { | ||
| email: 'user1@example.com', | ||
| password: 'password1', | ||
| }, | ||
| user2: { | ||
| email: 'user2@example.com', | ||
| password: 'password2', | ||
| }, | ||
| }; | ||
|
|
||
| export default MOCK_USERS; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,161 @@ | ||
| import { INestApplication, ValidationPipe } from '@nestjs/common'; | ||
| import { TestingModule } from '@nestjs/testing'; | ||
| import { TestModuleFactory } from '../factory/test-module.factory'; | ||
| import { ValidationException } from 'common/exceptions/validation.exception'; | ||
| import { BaseExceptionsFilter } from 'common/filters/base-exception.filter'; | ||
| import { AllExceptionsFilter } from 'common/filters/all-exception.filter'; | ||
| import MOCK_USERS from '../mocks/user-mocks'; | ||
| import request from 'supertest'; | ||
| import { PostgresContainer } from '../utils/postgres-container'; | ||
|
|
||
| describe('AuthModule', () => { | ||
| let testingModule: TestingModule; | ||
| let app: INestApplication; | ||
| let registeredUser: { email: string; password: string }; | ||
| let authToken = ''; | ||
| beforeAll(async () => { | ||
| const postgresContainer = await PostgresContainer.getInstance(); | ||
|
|
||
| testingModule = await TestModuleFactory.createTestModule( | ||
| postgresContainer.getConnectionUri(), | ||
| ); | ||
| app = testingModule.createNestApplication(); | ||
|
|
||
| app.useGlobalFilters(new AllExceptionsFilter(), new BaseExceptionsFilter()); | ||
| app.useGlobalPipes( | ||
| new ValidationPipe({ | ||
| exceptionFactory: (errors) => { | ||
| return new ValidationException(errors); | ||
| }, | ||
| transform: true, | ||
| whitelist: true, | ||
| validationError: { target: false }, | ||
| }), | ||
| ); | ||
|
|
||
| await app.init(); | ||
| }, 60000); | ||
|
|
||
| afterAll(async () => { | ||
| await app.close(); | ||
| }, 60000); | ||
| const generateValidUserDto = () => ({ | ||
| email: MOCK_USERS.user2.email, | ||
| password: MOCK_USERS.user2.password, | ||
| }); | ||
| describe('Authentication Flow', () => { | ||
| beforeAll(async () => { | ||
| // Ensure we have a registered user for login tests | ||
| if (!registeredUser) { | ||
| registeredUser = generateValidUserDto(); | ||
| await request(app.getHttpServer()) | ||
| .post('/users/register') | ||
| .send(registeredUser) | ||
| .expect(201); | ||
| } | ||
| }); | ||
|
|
||
| describe('POST /auth/login', () => { | ||
| it('should login with valid credentials', async () => { | ||
| const response = await request(app.getHttpServer()) | ||
| .post('/auth/login') | ||
| .send({ | ||
| login: registeredUser.email, | ||
| password: registeredUser.password, | ||
| }) | ||
| .expect(200); | ||
|
|
||
| expect(response.body).toHaveProperty('accessToken'); | ||
| expect(response.body).toHaveProperty('user'); | ||
| expect(response.body.user).toHaveProperty( | ||
| 'email', | ||
| registeredUser.email.toLowerCase(), | ||
| ); | ||
|
|
||
| authToken = response.body.accessToken; | ||
| }); | ||
|
|
||
| it('should return 401 with invalid email', async () => { | ||
| const response = await request(app.getHttpServer()) | ||
| .post('/auth/login') | ||
| .send({ | ||
| login: 'nonexistent@example.com', | ||
| password: registeredUser.password, | ||
| }) | ||
| .expect(401); | ||
|
|
||
| expect(response.body.message).toContain('Invalid login or password'); | ||
| }); | ||
|
|
||
| it('should return 401 with invalid password', async () => { | ||
| const response = await request(app.getHttpServer()) | ||
| .post('/auth/login') | ||
| .send({ | ||
| login: registeredUser.email, | ||
| password: 'wrongpassword', | ||
| }) | ||
| .expect(401); | ||
|
|
||
| expect(response.body.message).toContain('Invalid login or password'); | ||
| }); | ||
|
|
||
| it('should return 400 when login is missing', async () => { | ||
| const response = await request(app.getHttpServer()) | ||
| .post('/auth/login') | ||
| .send({ | ||
| password: registeredUser.password, | ||
| }) | ||
| .expect(400); | ||
|
|
||
| expect(response.body.message).toBe('Validation Failed'); | ||
| expect(response.body.errors).toBeDefined(); | ||
| }); | ||
|
|
||
| it('should return 400 when password is missing', async () => { | ||
| const response = await request(app.getHttpServer()) | ||
| .post('/auth/login') | ||
| .send({ | ||
| login: registeredUser.email, | ||
| }) | ||
| .expect(400); | ||
|
|
||
| expect(response.body.message).toBe('Validation Failed'); | ||
| expect(response.body.errors).toBeDefined(); | ||
| }); | ||
| }); | ||
|
|
||
| describe('GET /auth/me', () => { | ||
| it('should return current user when authenticated', async () => { | ||
| const response = await request(app.getHttpServer()) | ||
| .get('/auth/me') | ||
| .set('Authorization', `Bearer ${authToken}`) | ||
| .expect(200); | ||
|
|
||
| expect(response.body).toHaveProperty('user'); | ||
| expect(response.body.user).toHaveProperty( | ||
| 'email', | ||
| registeredUser.email.toLowerCase(), | ||
| ); | ||
| expect(response.body.user).toHaveProperty('id'); | ||
| expect(response.body.user).not.toHaveProperty('password'); | ||
| }); | ||
|
|
||
| it('should return 401 when not authenticated', async () => { | ||
| const response = await request(app.getHttpServer()) | ||
| .get('/auth/me') | ||
| .expect(401); | ||
|
|
||
| expect(response.body.message).toContain('Unauthorized'); | ||
| }); | ||
|
|
||
| it('should return 401 with malformed authorization header', async () => { | ||
| const response = await request(app.getHttpServer()) | ||
| .get('/auth/me') | ||
| .set('Authorization', 'InvalidFormat') | ||
| .expect(401); | ||
|
|
||
| expect(response.body.message).toContain('Unauthorized'); | ||
| }); | ||
| }); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
test/users/mock/users.ts