Skip to content

Commit

Permalink
test: cover the whole session controler and service use cases (#159)
Browse files Browse the repository at this point in the history
- Coverage the whole session use case

---------

Co-authored-by: Giovanni Bassi <giggio@giggio.net>
  • Loading branch information
BertBR and giggio authored May 23, 2024
1 parent 48d9e1b commit 38cccef
Show file tree
Hide file tree
Showing 2 changed files with 267 additions and 16 deletions.
80 changes: 76 additions & 4 deletions src/sessions/sessions.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { JwtService } from '@nestjs/jwt';
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaService } from 'src/prisma/prisma.service';
import { SessionsController } from './sessions.controller';
import { SessionsService } from './sessions.service';
import { PrismaService } from 'src/prisma/prisma.service';
import { JwtService } from '@nestjs/jwt';

describe('SessionsController', () => {
let controller: SessionsController;
let service: SessionsService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
Expand All @@ -17,12 +18,83 @@ describe('SessionsController', () => {
return {};
}
})
.overrideProvider(SessionsService)
.useValue({
login: jest.fn().mockResolvedValue('token'),
show: jest.fn().mockResolvedValue('token'),
delete: jest.fn().mockResolvedValue('token'),
})
.compile();

module.useLogger({
log: jest.fn(),
error: jest.fn(),
warn: jest.fn(),
verbose: jest.fn(),
});
controller = module.get<SessionsController>(SessionsController);
service = module.get<SessionsService>(SessionsService);
});

it('should return a token', async () => {
const expectedResponse = {
statusCode: 200,
message: 'Successfully logged in',
respData: 'token',
};
const res = await controller.login(
{
email: 'test@test.com',
password: 'password',
},
'127.0.0.1',
'user-agent',
);
expect(res).toEqual(expectedResponse);
});

it('should throw an error when login', async () => {
jest.spyOn(service, 'login').mockRejectedValue(new Error('Error'));
await expect(
controller.login(
{
email: 'test@test.com',
password: 'password',
},
'127.0.0.1',
'user-agent',
),
).rejects.toThrow();
});

it('should show a session', async () => {
const expectedResponse = {
statusCode: 200,
message: 'Successfully logged in',
respData: 'token',
};
const res = await controller.show({ user: { userId: 1 } });
expect(res).toEqual(expectedResponse);
});

it('should throw an error when show an user', async () => {
jest.spyOn(service, 'show').mockRejectedValue(new Error('Error'));
await expect(controller.show({ user: { userId: 1 } })).rejects.toThrow();
});

it('should delete a session', async () => {
const expectedResponse = {
statusCode: 200,
message: 'Successfully logged out',
respData: 'token',
};

const res = await controller.delete({ user: { userId: 1 } });
expect(res).toEqual(expectedResponse);
});

it('should be defined', () => {
expect(controller).toBeDefined();
it('should throw an error when delete a session', async () => {
jest.spyOn(service, 'delete').mockRejectedValue(new Error('Error'));
await expect(controller.delete({ user: { userId: 1 } })).rejects.toThrow();
});
});
203 changes: 191 additions & 12 deletions src/sessions/sessions.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,205 @@
import { Test, TestingModule } from '@nestjs/testing';
import { SessionsService } from './sessions.service';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from 'src/prisma/prisma.service';
import * as bcrypt from 'bcrypt';
import { PrismaService } from '../prisma/prisma.service';
import { SessionsService } from './sessions.service';

jest.mock('bcrypt');
describe('SessionsService', () => {
let service: SessionsService;
let prismaService: PrismaService;
let jwtService: JwtService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [SessionsService, JwtService],
})
.useMocker((token) => {
if (token === PrismaService) {
return {};
}
})
.compile();
providers: [
SessionsService,
{
provide: PrismaService,
useValue: {
user: {
findUnique: jest.fn(),
},
session: {
updateMany: jest.fn(),
create: jest.fn(),
update: jest.fn(),
},
},
},
{
provide: JwtService,
useValue: {
sign: jest.fn(),
},
},
],
}).compile();

service = module.get<SessionsService>(SessionsService);
prismaService = module.get<PrismaService>(PrismaService);
jwtService = module.get<JwtService>(JwtService);
});

describe('login', () => {
it('should throw an error if user is not found', async () => {
(prismaService.user.findUnique as jest.Mock).mockResolvedValue(null);

await expect(
service.login({
login: 'test',
password: 'password',
ip: '127.0.0.1',
userAgent: 'test',
}),
).rejects.toThrow('Usuário não encontrado');
});

it('should throw an error if password is incorrect', async () => {
const user = { id: 1, login: 'test', password: 'hashedpassword' };
(prismaService.user.findUnique as jest.Mock).mockResolvedValue(user);
(bcrypt.compare as jest.Mock).mockResolvedValue(false);

await expect(
service.login({
login: 'test',
password: 'wrongpassword',
ip: '127.0.0.1',
userAgent: 'test',
}),
).rejects.toThrow('Senha incorreta');
});

it('should return a token if login is successful', async () => {
const user = { id: 1, login: 'test', password: 'hashedpassword' };
const session = { id: 1, userId: 1 };
const token = 'token';
(prismaService.user.findUnique as jest.Mock).mockResolvedValue(user);
(bcrypt.compare as jest.Mock).mockResolvedValue(true);
(prismaService.session.updateMany as jest.Mock).mockResolvedValue({});
(prismaService.session.create as jest.Mock).mockResolvedValue(session);
(jwtService.sign as jest.Mock).mockReturnValue(token);

const result = await service.login({
login: 'test',
password: 'password',
ip: '127.0.0.1',
userAgent: 'test',
});

expect(result).toEqual({ token });
expect(prismaService.user.findUnique).toHaveBeenCalledWith({
where: { login: 'test' },
});
expect(bcrypt.compare).toHaveBeenCalledWith('password', 'hashedpassword');
expect(prismaService.session.updateMany).toHaveBeenCalledWith({
where: { user: { login: 'test' }, active: true },
data: { active: false, updatedAt: expect.any(String) },
});
expect(prismaService.session.create).toHaveBeenCalledWith({
data: {
userId: user.id,
ip: '127.0.0.1',
userAgent: 'test',
createdAt: expect.any(String),
},
});
expect(jwtService.sign).toHaveBeenCalledWith({
sessionId: session.id,
userId: user.id,
});
});
});

describe('show', () => {
it('should return user data if user is found', async () => {
const user = {
id: '1',
name: 'Test User',
login: 'test',
phone: '123456789',
accessLevel: 'admin',
createdAt: new Date(),
};
(prismaService.user.findUnique as jest.Mock).mockResolvedValue(user);

const result = await service.show('1');

expect(result).toEqual(user);
expect(prismaService.user.findUnique).toHaveBeenCalledWith({
where: { id: '1' },
select: {
id: true,
name: true,
login: true,
phone: true,
accessLevel: true,
createdAt: true,
},
});
});

it('should return null if user is not found', async () => {
(prismaService.user.findUnique as jest.Mock).mockResolvedValue(null);

const result = await service.show('1');

expect(result).toBeNull();
expect(prismaService.user.findUnique).toHaveBeenCalledWith({
where: { id: '1' },
select: {
id: true,
name: true,
login: true,
phone: true,
accessLevel: true,
createdAt: true,
},
});
});
});

it('should be defined', () => {
expect(service).toBeDefined();
describe('delete', () => {
it('should deactivate session if session and user match', async () => {
const session = {
id: '1',
userId: '1',
updatedAt: new Date(),
active: false,
};
(prismaService.session.update as jest.Mock).mockResolvedValue(session);

const result = await service.delete({ sessionId: '1', userId: '1' });

expect(result).toEqual(session);
expect(prismaService.session.update).toHaveBeenCalledWith({
where: {
id: '1',
userId: '1',
},
data: {
updatedAt: expect.any(String),
active: false,
},
});
});

it('should return null if session does not exist', async () => {
(prismaService.session.update as jest.Mock).mockResolvedValue(null);

const result = await service.delete({ sessionId: '1', userId: '1' });

expect(result).toBeNull();
expect(prismaService.session.update).toHaveBeenCalledWith({
where: {
id: '1',
userId: '1',
},
data: {
updatedAt: expect.any(String),
active: false,
},
});
});
});
});

0 comments on commit 38cccef

Please sign in to comment.