Skip to content

Commit

Permalink
Merge pull request #11 from fga-eps-mds/dev
Browse files Browse the repository at this point in the history
Pushing the dev to main
  • Loading branch information
DaviMatheus authored Jul 31, 2024
2 parents c5dc001 + daec785 commit 100ff51
Show file tree
Hide file tree
Showing 7 changed files with 710 additions and 0 deletions.
3 changes: 3 additions & 0 deletions jest.config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { Config } from 'jest';
import * as dotenv from 'dotenv';

dotenv.config();
const config: Config = {
preset: 'ts-jest',
testEnvironment: 'node',
Expand All @@ -16,6 +18,7 @@ const config: Config = {
moduleNameMapper: {
'^src/(.*)$': '<rootDir>/src/$1',
},
setupFiles: ['dotenv/config'],
};

export default config;
177 changes: 177 additions & 0 deletions test/auth.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ConfigService } from '@nestjs/config';
import { UnauthorizedException } from '@nestjs/common';
import { LoginDto } from 'src/users/dtos/login.dto';
import { Request, Response } from 'express';
import { AuthService } from 'src/auth/auth.service';
import { AuthController } from 'src/auth/auth.controller';

describe('AuthController', () => {
let authController: AuthController;
let authService: AuthService;
let configService: ConfigService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AuthController],
providers: [
{
provide: AuthService,
useValue: {
validateUser: jest.fn(),
login: jest.fn(),
},
},
{
provide: ConfigService,
useValue: {
get: jest.fn(),
},
},
],
}).compile();

authController = module.get<AuthController>(AuthController);
authService = module.get<AuthService>(AuthService);
configService = module.get<ConfigService>(ConfigService);

// Defina as variáveis de ambiente para os testes
process.env.FRONTEND_URL = 'http://localhost:3000';
});

describe('login', () => {
it('should return a token if credentials are valid', async () => {
const loginDto: LoginDto = {
email: '[email protected]',
password: 'password',
};
const user = { id: 'user-id', email: '[email protected]' };
const token = 'token';
authService.validateUser = jest.fn().mockResolvedValue(user);
authService.login = jest.fn().mockResolvedValue({ access_token: token });

const result = await authController.login(loginDto);

expect(authService.validateUser).toHaveBeenCalledWith(
loginDto.email,
loginDto.password,
);
expect(authService.login).toHaveBeenCalledWith(user);
expect(result).toEqual({ access_token: token });
});

it('should throw UnauthorizedException if credentials are invalid', async () => {
const loginDto: LoginDto = {
email: '[email protected]',
password: 'password',
};
authService.validateUser = jest.fn().mockResolvedValue(null);

await expect(authController.login(loginDto)).rejects.toThrow(
UnauthorizedException,
);
});
});

describe('googleAuth', () => {
it('should log initiation of Google auth', async () => {
const logSpy = jest.spyOn(authController['logger'], 'log');
const frontendUrl = process.env.FRONTEND_URL;
configService.get = jest.fn().mockReturnValue(frontendUrl);

await authController.googleAuth();

expect(logSpy).toHaveBeenCalledWith(`front url: ${frontendUrl}`);
expect(logSpy).toHaveBeenCalledWith(
'AuthController - Google Auth Initiated',
);
});
});

describe('googleAuthRedirect', () => {
it('should redirect to OAuth URL if accessToken is present', () => {
const req = { user: { accessToken: 'token' } } as unknown as Request;
const res = { redirect: jest.fn() } as unknown as Response;
const frontendUrl = process.env.FRONTEND_URL;
configService.get = jest.fn().mockReturnValue(frontendUrl);
const logSpy = jest.spyOn(authController['logger'], 'log');

authController.googleAuthRedirect(req, res);

expect(logSpy).toHaveBeenCalledWith(`front url: ${frontendUrl}`);
expect(logSpy).toHaveBeenCalledWith(
'AuthController - Google Callback Request:',
req.user,
);
expect(res.redirect).toHaveBeenCalledWith(
`${frontendUrl}/oauth?token=token`,
);
});

it('should redirect to registration URL if accessToken is not present', () => {
const req = { user: {} } as Request;
const res = { redirect: jest.fn() } as unknown as Response;
const frontendUrl = process.env.FRONTEND_URL;
configService.get = jest.fn().mockReturnValue(frontendUrl);
const logSpy = jest.spyOn(authController['logger'], 'log');

authController.googleAuthRedirect(req, res);

expect(logSpy).toHaveBeenCalledWith(`front url: ${frontendUrl}`);
expect(logSpy).toHaveBeenCalledWith(
'AuthController - Google Callback Request:',
req.user,
);
expect(res.redirect).toHaveBeenCalledWith(`${frontendUrl}/cadastro`);
});
});

describe('microsoftAuth', () => {
it('should log initiation of Microsoft auth', async () => {
const logSpy = jest.spyOn(authController['logger'], 'log');
const frontendUrl = process.env.FRONTEND_URL;
configService.get = jest.fn().mockReturnValue(frontendUrl);

await authController.microsoftAuth();

expect(logSpy).toHaveBeenCalledWith(`front url: ${frontendUrl}`);
expect(logSpy).toHaveBeenCalledWith(
'AuthController - Microsoft Auth Initiated',
);
});
});

describe('microsoftAuthRedirect', () => {
it('should redirect to OAuth URL if accessToken is present', () => {
const req = { user: { accessToken: 'token' } } as unknown as Request;
const res = { redirect: jest.fn() } as unknown as Response;
const frontendUrl = process.env.FRONTEND_URL;
configService.get = jest.fn().mockReturnValue(frontendUrl);
const logSpy = jest.spyOn(authController['logger'], 'log');

authController.microsoftAuthRedirect(req, res);

expect(logSpy).toHaveBeenCalledWith(
'AuthController - Microsoft Callback Request:',
JSON.stringify(req.user),
);
expect(res.redirect).toHaveBeenCalledWith(`${frontendUrl}/oauth?token=token`);
});

it('should redirect to registration URL if accessToken is not present', () => {
const req = { user: {} } as Request;
const res = { redirect: jest.fn() } as unknown as Response;
const frontendUrl = process.env.FRONTEND_URL;
configService.get = jest.fn().mockReturnValue(frontendUrl);
const logSpy = jest.spyOn(authController['logger'], 'log');

authController.microsoftAuthRedirect(req, res);

expect(logSpy).toHaveBeenCalledWith(
'AuthController - Microsoft Callback Request:',
JSON.stringify(req.user),
);
expect(res.redirect).toHaveBeenCalledWith(`${frontendUrl}/cadastro`);
});
});
});
77 changes: 77 additions & 0 deletions test/auth.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { Test, TestingModule } from '@nestjs/testing';
import { JwtService } from '@nestjs/jwt';
import { UnauthorizedException } from '@nestjs/common';
import { AuthService } from 'src/auth/auth.service';
import { UsersService } from 'src/users/users.service';

describe('AuthService', () => {
let authService: AuthService;
let usersService: UsersService;
let jwtService: JwtService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
AuthService,
{
provide: UsersService,
useValue: {
findByEmail: jest.fn(),
},
},
{
provide: JwtService,
useValue: {
sign: jest.fn(),
},
},
],
}).compile();

authService = module.get<AuthService>(AuthService);
usersService = module.get<UsersService>(UsersService);
jwtService = module.get<JwtService>(JwtService);
});

describe('validateUser', () => {
it('should throw UnauthorizedException if credentials are invalid', async () => {
const email = '[email protected]';
const password = 'wrongpassword';

jest.spyOn(usersService, 'findByEmail').mockResolvedValue(null);

await expect(authService.validateUser(email, password)).rejects.toThrow(
UnauthorizedException,
);
});
});

describe('login', () => {
it('should return a token and user data', async () => {
const user = {
_id: 'user-id',
name: 'Test User',
email: '[email protected]',
role: 'user',
};
const token = 'jwt-token';
jest.spyOn(jwtService, 'sign').mockReturnValue(token);

const result = await authService.login(user);

expect(jwtService.sign).toHaveBeenCalledWith({
id: user._id,
name: user.name,
email: user.email,
sub: user._id,
role: user.role,
});
expect(result).toEqual({
id: user._id,
name: user.name,
email: user.email,
accessToken: token,
});
});
});
});
Loading

0 comments on commit 100ff51

Please sign in to comment.