Skip to content
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

Feature/login #2

Merged
merged 6 commits into from
Apr 30, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add testing for modules
FerreiroAlberto committed Apr 30, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
commit 49aeb104ff1fc4fcd7087d1f4ab2fa0b20d7d474
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -79,7 +79,9 @@
"coveragePathIgnorePatterns": [
"module",
"dto",
"entity"
"entity",
"main",
"prisma"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
16 changes: 16 additions & 0 deletions prisma/migrations/20240430100624_adjust_policies/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
Warnings:
- A unique constraint covering the columns `[policyNumber]` on the table `Policy` will be added. If there are existing duplicate values, this will fail.
- Added the required column `carAge` to the `Policy` table without a default value. This is not possible if the table is not empty.
- Added the required column `plateNumber` to the `Policy` table without a default value. This is not possible if the table is not empty.
- Added the required column `policyType` to the `Policy` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "Policy" ADD COLUMN "carAge" INTEGER NOT NULL,
ADD COLUMN "plateNumber" TEXT NOT NULL,
ADD COLUMN "policyType" TEXT NOT NULL;

-- CreateIndex
CREATE UNIQUE INDEX "Policy_policyNumber_key" ON "Policy"("policyNumber");
2 changes: 1 addition & 1 deletion prisma/migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "postgresql"
provider = "postgresql"
5 changes: 4 additions & 1 deletion prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -29,7 +29,10 @@ id String @id @default(uuid())
userId String
carMake String
carModel String
policyNumber Int @default(autoincrement())
carAge Int
plateNumber String
policyType String
policyNumber Int @default(autoincrement()) @unique
claims Claim[]
user User @relation(fields: [userId], references: [id])
}
3 changes: 2 additions & 1 deletion src/policies/dto/create-policy.dto.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
export class CreatePolicyDto {
carMake: string;
carModel: string;
carAge: string;
carAge: number;
plateNumber: string;
policyType: string;
userId: string;
}
2 changes: 1 addition & 1 deletion src/policies/dto/update-policy.dto.ts
Original file line number Diff line number Diff line change
@@ -4,7 +4,7 @@ import { CreatePolicyDto } from './create-policy.dto';
export class UpdatePolicyDto extends PartialType(CreatePolicyDto) {
carMake?: string;
carModel?: string;
carAge?: string;
carAge?: number;
plateNumber?: string;
policyType: string;
}
4 changes: 2 additions & 2 deletions src/policies/entities/policy.entity.ts
Original file line number Diff line number Diff line change
@@ -3,8 +3,8 @@ export class Policy {
userId: number;
carMake: string;
carModel: string;
carAge: string;
plateNumber: string;
carAge: number;
plateNumber: number;
policyNumber: string;
policyType: string;
claims: Claim[];
70 changes: 69 additions & 1 deletion src/policies/policies.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,43 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PoliciesController } from './policies.controller';
import { PoliciesService } from './policies.service';
import { PrismaService } from '../prisma/prisma.service';
import { CreatePolicyDto } from './dto/create-policy.dto';

const mockPoliciesService = {
findAll: jest.fn().mockResolvedValue([]),
findOne: jest.fn().mockResolvedValue({}),
create: jest.fn().mockResolvedValue({}),
update: jest.fn().mockResolvedValue({}),
delete: jest.fn().mockResolvedValue({}),
};

const mockPrismaService = {
policy: {
findMany: jest.fn().mockResolvedValue([]),
findUnique: jest.fn().mockReturnValue({}),
create: jest.fn().mockReturnValue({}),
update: jest.fn().mockReturnValue({}),
},
};

describe('PoliciesController', () => {
let controller: PoliciesController;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [PoliciesController],
providers: [PoliciesService],
providers: [
PoliciesService,
{
provide: PoliciesService,
useValue: mockPoliciesService,
},
{
provide: PrismaService,
useValue: mockPrismaService,
},
],
}).compile();

controller = module.get<PoliciesController>(PoliciesController);
@@ -17,4 +46,43 @@ describe('PoliciesController', () => {
it('should be defined', () => {
expect(controller).toBeDefined();
});
describe('When we use the method findAll', () => {
it('should return all users', async () => {
const result = await controller.findAll();
expect(mockPoliciesService.findAll).toHaveBeenCalled();
expect(result).toEqual([]);
});
});
describe('When we use the method findOne', () => {
it('should return the user with the id', async () => {
const result = await controller.findOne('1');
expect(mockPoliciesService.findOne).toHaveBeenCalled();
expect(result).toEqual({});
});
});
describe('When we use the method create', () => {
it('should create a new policy', async () => {
const mockPolicyDto = {} as CreatePolicyDto;
const result = await controller.create('1', mockPolicyDto);
expect(mockPoliciesService.create).toHaveBeenCalled();
expect(result).toEqual({});
});
});
describe('When we use the method update', () => {
it('should update a policy', async () => {
const mockPolicyDto = {
policyType: '12345',
} as CreatePolicyDto;
const result = await controller.update('1', mockPolicyDto);
expect(mockPoliciesService.update).toHaveBeenCalled();
expect(result).toEqual({});
});
});
describe('When we use the method delete', () => {
it('should delete and return a policy', async () => {
const result = await controller.delete('1');
expect(mockPoliciesService.delete).toHaveBeenCalled();
expect(result).toEqual({});
});
});
});
22 changes: 15 additions & 7 deletions src/policies/policies.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
} from '@nestjs/common';
import { PoliciesService } from './policies.service';
import { CreatePolicyDto } from './dto/create-policy.dto';
import { UpdatePolicyDto } from './dto/update-policy.dto';
@@ -8,8 +16,8 @@ export class PoliciesController {
constructor(private readonly policiesService: PoliciesService) {}

@Post()
create(@Body() createPolicyDto: CreatePolicyDto) {
return this.policiesService.create(createPolicyDto);
create(@Param('id') id: string, @Body() createPolicyDto: CreatePolicyDto) {
return this.policiesService.create(id, createPolicyDto);
}

@Get()
@@ -19,16 +27,16 @@ export class PoliciesController {

@Get(':id')
findOne(@Param('id') id: string) {
return this.policiesService.findOne(+id);
return this.policiesService.findOne(id);
}

@Patch(':id')
update(@Param('id') id: string, @Body() updatePolicyDto: UpdatePolicyDto) {
return this.policiesService.update(+id, updatePolicyDto);
return this.policiesService.update(id, updatePolicyDto);
}

@Delete(':id')
remove(@Param('id') id: string) {
return this.policiesService.remove(+id);
delete(@Param('id') id: string) {
return this.policiesService.delete(id);
}
}
79 changes: 78 additions & 1 deletion src/policies/policies.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,28 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PoliciesService } from './policies.service';
import { PrismaService } from '../prisma/prisma.service';
import { CreatePolicyDto } from './dto/create-policy.dto';
import { UpdatePolicyDto } from './dto/update-policy.dto';

const mockPrisma = {
policy: {
findMany: jest.fn().mockResolvedValue([]),
findUnique: jest.fn().mockReturnValue({}),
create: jest.fn().mockReturnValue({}),
update: jest.fn().mockReturnValue({}),
delete: jest.fn().mockReturnValue({}),
},
};

describe('PoliciesService', () => {
let service: PoliciesService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [PoliciesService],
providers: [
{ provide: PrismaService, useValue: mockPrisma },
PoliciesService,
],
}).compile();

service = module.get<PoliciesService>(PoliciesService);
@@ -15,4 +31,65 @@ describe('PoliciesService', () => {
it('should be defined', () => {
expect(service).toBeDefined();
});
describe('When we use the method findOne', () => {
it('Then it should return the user with the right id', async () => {
const result = await service.findOne('1');
expect(mockPrisma.policy.findUnique).toHaveBeenCalled();
expect(result).toEqual({});
});

it('Then it should throw an error if the user is not found', async () => {
mockPrisma.policy.findUnique.mockReturnValueOnce(null);
expect(service.findOne('1')).rejects.toThrow('Policy 1 not found');
});
});
describe('When we use the method findAll', () => {
it('Then it should return all the users', async () => {
const result = await service.findAll();
expect(mockPrisma.policy.findMany).toHaveBeenCalled();
expect(result).toEqual([]);
});
});
describe('When we use the method create', () => {
it('Then it should return the new user', async () => {
const result = await service.create('1', {} as CreatePolicyDto);
expect(mockPrisma.policy.create).toHaveBeenCalled();

expect(result).toEqual({});
});
});
describe('When we use the method update', () => {
it('Then it should return the updated user', async () => {
const result = await service.update('1', {} as UpdatePolicyDto);
expect(mockPrisma.policy.update).toHaveBeenCalled();
expect(result).toEqual({});
});

it('Then it should throw an error if the user is not found', async () => {
mockPrisma.policy.findUnique.mockReturnValueOnce(null);
mockPrisma.policy.update.mockRejectedValueOnce(
new Error('Policy not found'),
);
expect(service.update('1', {} as UpdatePolicyDto)).rejects.toThrow(
'Policy 1 not found',
);
});
});
describe('When we use the method delete', () => {
it('Then it should return the deleted user', async () => {
mockPrisma.policy.findUnique.mockReturnValueOnce({});
mockPrisma.policy.delete.mockReturnValueOnce({});
const result = await service.delete('1');
expect(mockPrisma.policy.delete).toHaveBeenCalled();
expect(result).toEqual({});
});

it('Then it should throw an error if the user is not found', async () => {
mockPrisma.policy.findUnique.mockReturnValueOnce(null);
mockPrisma.policy.delete.mockRejectedValueOnce(
new Error('Policy not found'),
);
expect(service.delete('1')).rejects.toThrow('Policy 1 not found');
});
});
});
66 changes: 55 additions & 11 deletions src/policies/policies.service.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,70 @@
import { Injectable } from '@nestjs/common';
import { Injectable, NotFoundException } from '@nestjs/common';
import { CreatePolicyDto } from './dto/create-policy.dto';
import { UpdatePolicyDto } from './dto/update-policy.dto';
import { PrismaService } from '../prisma/prisma.service';

const select = {
id: true,
carMake: true,
carModel: true,
carAge: true,
plateNumber: true,
policyNumber: true,
claims: {
select: {
status: true,
type: true,
phoneNumber: true,
address: true,
},
},
};

@Injectable()
export class PoliciesService {
create(createPolicyDto: CreatePolicyDto) {
return 'This action adds a new policy';
constructor(private prisma: PrismaService) {}
async create(id: string, data: CreatePolicyDto) {
return this.prisma.policy.create({
data,
select,
});
}

findAll() {
return `This action returns all policies`;
async findAll() {
return this.prisma.policy.findMany({ select });
}

findOne(id: number) {
return `This action returns a #${id} policy`;
async findOne(id: string) {
const policy = await this.prisma.policy.findUnique({
where: { id },
select,
});
if (!policy) {
throw new NotFoundException(`Policy ${id} not found`);
}
return policy;
}

update(id: number, updatePolicyDto: UpdatePolicyDto) {
return `This action updates a #${id} policy`;
async update(id: string, data: UpdatePolicyDto) {
try {
return await this.prisma.policy.update({
where: { id },
data,
select,
});
} catch (error) {
throw new NotFoundException(`Policy ${id} not found`);
}
}

remove(id: number) {
return `This action removes a #${id} policy`;
async delete(id: string) {
try {
return await this.prisma.policy.delete({
where: { id },
select,
});
} catch (error) {
throw new NotFoundException(`Policy ${id} not found`);
}
}
}
62 changes: 61 additions & 1 deletion src/users/users.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,42 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { PrismaService } from '../prisma/prisma.service';

const mockUsersService = {
findAll: jest.fn().mockResolvedValue([]),
findOne: jest.fn().mockResolvedValue({}),
findForLogin: jest.fn().mockResolvedValue({}),
create: jest.fn().mockResolvedValue({}),
update: jest.fn().mockResolvedValue({}),
};

const mockPrismaService = {
user: {
findMany: jest.fn().mockResolvedValue([]),
findUnique: jest.fn().mockReturnValue({}),
create: jest.fn().mockReturnValue({}),
update: jest.fn().mockReturnValue({}),
},
};

describe('UsersController', () => {
let controller: UsersController;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UsersController],
providers: [UsersService],
providers: [
{
provide: UsersService,
useValue: mockUsersService,
},
{
provide: PrismaService,
useValue: mockPrismaService,
},
],
}).compile();

controller = module.get<UsersController>(UsersController);
@@ -17,4 +45,36 @@ describe('UsersController', () => {
it('should be defined', () => {
expect(controller).toBeDefined();
});
describe('When we use the method findAll', () => {
it('should return all users', async () => {
const result = await controller.findAll();
expect(mockUsersService.findAll).toHaveBeenCalled();
expect(result).toEqual([]);
});
});
describe('When we use the method findOne', () => {
it('should return the user with the id', async () => {
const result = await controller.findOne('1');
expect(mockUsersService.findOne).toHaveBeenCalled();
expect(result).toEqual({});
});
});
describe('When we use the method register', () => {
it('should create a new user', async () => {
const mockUserDto = {} as CreateUserDto;
const result = await controller.register(mockUserDto);
expect(mockUsersService.create).toHaveBeenCalled();
expect(result).toEqual({});
});
});
describe('When we use the method update', () => {
it('should update a user', async () => {
const mockUserDto = {
password: '12345',
} as CreateUserDto;
const result = await controller.update('1', mockUserDto);
expect(mockUsersService.update).toHaveBeenCalled();
expect(result).toEqual({});
});
});
});
17 changes: 2 additions & 15 deletions src/users/users.controller.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,4 @@
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
} from '@nestjs/common';
import { Controller, Get, Post, Body, Patch, Param } from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
@@ -16,7 +8,7 @@ export class UsersController {
constructor(private readonly usersService: UsersService) {}

@Post()
create(@Body() createUserDto: CreateUserDto) {
register(@Body() createUserDto: CreateUserDto) {
return this.usersService.create(createUserDto);
}

@@ -34,9 +26,4 @@ export class UsersController {
update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
return this.usersService.update(id, updateUserDto);
}

@Delete(':id')
remove(@Param('id') id: string) {
return this.usersService.delete(id);
}
}
76 changes: 75 additions & 1 deletion src/users/users.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from './users.service';
import { PrismaService } from '../prisma/prisma.service';

const mockPrisma = {
user: {
findMany: jest.fn().mockResolvedValue([]),
findUnique: jest.fn().mockReturnValue({}),
create: jest.fn().mockReturnValue({}),
update: jest.fn().mockReturnValue({}),
},
};
describe('UsersService', () => {
let service: UsersService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UsersService],
providers: [
{ provide: PrismaService, useValue: mockPrisma },
UsersService,
],
}).compile();

service = module.get<UsersService>(UsersService);
@@ -15,4 +27,66 @@ describe('UsersService', () => {
it('should be defined', () => {
expect(service).toBeDefined();
});
describe('When we use the method findOne', () => {
it('Then it should return the user with the right id', async () => {
const result = await service.findOne('1');
expect(mockPrisma.user.findUnique).toHaveBeenCalled();
expect(result).toEqual({});
});

it('Then it should throw an error if the user is not found', async () => {
mockPrisma.user.findUnique.mockReturnValueOnce(null);
expect(service.findOne('1')).rejects.toThrow('User 1 not found');
});
});
describe('When we use the method findAll', () => {
it('Then it should return all the users', async () => {
const result = await service.findAll();
expect(mockPrisma.user.findMany).toHaveBeenCalled();
expect(result).toEqual([]);
});
});
describe('When we use the method findForLogin', () => {
it('Then it should return the user with the matching email', async () => {
const result = await service.findForLogin('cara@papa.com');
expect(mockPrisma.user.findUnique).toHaveBeenCalled();
expect(result).toEqual({});
});

it('Then it should throw an error if the user is not found', async () => {
mockPrisma.user.findUnique.mockReturnValueOnce(null);
expect(service.findForLogin('cara@papa.com')).rejects.toThrow(
'Invalid input',
);
});
});
describe('When we use the method create', () => {
it('Then it should return the new user', async () => {
const result = await service.create({
name: 'pepe',
email: 'email',
age: 35,
licenseYear: 18,
password: '12345',
});
expect(mockPrisma.user.create).toHaveBeenCalled();

expect(result).toEqual({});
});
});
describe('When we use the method update', () => {
it('Then it should return the updated user', async () => {
const result = await service.update('1', {});
expect(mockPrisma.user.update).toHaveBeenCalled();
expect(result).toEqual({});
});

it('Then it should throw an error if the user is not found', async () => {
mockPrisma.user.findUnique.mockReturnValueOnce(null);
mockPrisma.user.update.mockRejectedValueOnce(new Error('User not found'));
expect(service.update('1', { name: 'pepito' })).rejects.toThrow(
'User 1 not found',
);
});
});
});
13 changes: 1 addition & 12 deletions src/users/users.service.ts
Original file line number Diff line number Diff line change
@@ -5,7 +5,7 @@ import {
} from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import { PrismaService } from '../prisma/prisma.service';

const select = {
id: true,
@@ -75,15 +75,4 @@ export class UsersService {
throw new NotFoundException(`User ${id} not found`);
}
}

async delete(id: string) {
try {
return await this.prisma.user.delete({
where: { id },
select,
});
} catch (error) {
throw new NotFoundException(`User ${id} not found`);
}
}
}