Skip to content

Commit

Permalink
Merge pull request #14 from fga-eps-mds/create_tests
Browse files Browse the repository at this point in the history
Adding Tests
  • Loading branch information
DaviMatheus authored Sep 8, 2024
2 parents 3c84a28 + 4730700 commit b9e3fe5
Show file tree
Hide file tree
Showing 5 changed files with 162 additions and 21 deletions.
27 changes: 13 additions & 14 deletions src/start_point/dtos/update-point.dto.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
export interface UpdatePointInterface {
_id: string;
name: string;
description?: string;
user?: string;
journeys?: string[];
order: Number;
createdAt: string;
__v: number;
updatedAt: string;
journey?: string;

}
_id: string;
name: string;
description?: string;
user?: string;
journeys?: string[];
order: Number;
createdAt: string;
__v: number;
updatedAt: string;
journey?: string;
}

export class UpdatePointOrderDto {
points: UpdatePointInterface[]
}
points: UpdatePointInterface[];
}
8 changes: 4 additions & 4 deletions src/start_point/point.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
import { PointService } from './point.service';
import { Request } from 'express';
import { CreateStartPointDto } from './dtos/create-start-point.dto';
import { UpdatePointOrderDto} from './dtos/update-point.dto';
import { UpdatePointOrderDto } from './dtos/update-point.dto';

@Controller('points')
export class PointController {
Expand Down Expand Up @@ -86,10 +86,10 @@ export class PointController {
@Patch('/update-point-order')
async updatePointOrder(
@Body()
pointsDto: UpdatePointOrderDto
pointsDto: UpdatePointOrderDto,
) {
console.log(pointsDto)
console.log(pointsDto);
const result = await this.pointService.updateOrder(pointsDto.points);
return result
return result;
}
}
2 changes: 1 addition & 1 deletion src/start_point/point.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const PointSchema = new mongoose.Schema(
description: { type: String, required: true },
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
journeys: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Journey' }],
order: { type:Number, default:0},
order: { type: Number, default: 0 },
},
{ timestamps: true, collection: 'startpoints' },
);
Expand Down
3 changes: 1 addition & 2 deletions src/start_point/point.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { Point } from './point.schema';
import { CreateStartPointDto } from './dtos/create-start-point.dto';
import { UpdatePointInterface} from './dtos/update-point.dto';
import { UpdatePointInterface } from './dtos/update-point.dto';

@Injectable()
export class PointService {
Expand All @@ -33,7 +33,6 @@ export class PointService {

const existent_array = this.findAll();


const newPoint = new this.pointModel({
...createStartPointDto,
user: userId,
Expand Down
143 changes: 143 additions & 0 deletions test/point.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { HttpService } from '@nestjs/axios';
import { NotFoundException, UnauthorizedException } from '@nestjs/common';
import { of } from 'rxjs';
import { PointService } from 'src/start_point/point.service';
import { Types } from 'mongoose';
import { UpdatePointInterface } from 'src/start_point/dtos/update-point.dto';

describe('PointService', () => {
let service: PointService;
Expand All @@ -19,6 +21,7 @@ describe('PointService', () => {
findByIdAndDelete: jest.fn(),
save: jest.fn(),
exec: jest.fn(),
bulkWrite: jest.fn(),
};

mockHttpService = {
Expand Down Expand Up @@ -60,6 +63,40 @@ describe('PointService', () => {
});
});

describe('create', () => {
it('should throw UnauthorizedException if token is invalid', async () => {
const createStartPointDto = {
name: 'Test Point',
description: 'Description',
};
const token = 'invalid-token';

jest.spyOn(service, 'validateTokenAndGetUserId').mockResolvedValue(null);

await expect(service.create(createStartPointDto, token)).rejects.toThrow(
UnauthorizedException,
);
});
});

describe('addPointToUser', () => {
it('should call the user service to add the point', async () => {
const userId = 'user-id';
const pointId = 'point-id';

// Simula uma resposta bem-sucedida do patch
jest.spyOn(mockHttpService, 'patch').mockReturnValue(of({}));

await service.addPointToUser(userId, pointId);

expect(mockHttpService.patch).toHaveBeenCalledWith(
`${process.env.USER_SERVICE_URL}/${userId}/add-point`,
{ pointId }
);
});

});

describe('update', () => {
it('should update a point and return the updated point', async () => {
const updateStartPointDto = {
Expand Down Expand Up @@ -227,4 +264,110 @@ describe('PointService', () => {
expect(userId).toBeNull();
});
});

describe('findByUserId', () => {
it('should return an array of points for the given userId', async () => {
const points = [
{ _id: 'point-id-1', name: 'Point 1', user: 'user-id' },
{ _id: 'point-id-2', name: 'Point 2', user: 'user-id' },
];
mockPointModel.find.mockReturnValueOnce({
exec: jest.fn().mockResolvedValue(points),
});

const result = await service.findByUserId('user-id');

expect(result).toEqual(points);
expect(mockPointModel.find).toHaveBeenCalledWith({ user: 'user-id' });
});
});

describe('addJourneyToPoint', () => {
it('should add a journey to the point and return the updated point', async () => {
const pointId = new Types.ObjectId().toHexString(); // Use um ID válido para o ponto
const journeyId = new Types.ObjectId().toHexString(); // Use um ID válido para a jornada
const objectId = new Types.ObjectId(journeyId);

const point = {
_id: pointId,
name: 'Test Point',
journeys: [],
save: jest.fn().mockResolvedValue({
_id: pointId,
name: 'Test Point',
journeys: [objectId],
}),
};

mockPointModel.findById.mockReturnValueOnce({
exec: jest.fn().mockResolvedValue(point),
});

const result = await service.addJourneyToPoint(pointId, journeyId);

expect(result).toEqual({
_id: pointId,
name: 'Test Point',
journeys: [objectId],
});
expect(mockPointModel.findById).toHaveBeenCalledWith(pointId);
expect(point.journeys).toContainEqual(objectId); // Use toContainEqual aqui
expect(point.save).toHaveBeenCalled();
});

it('should throw NotFoundException if point does not exist', async () => {
const pointId = new Types.ObjectId().toHexString(); // Use um ID válido para o ponto
const journeyId = new Types.ObjectId().toHexString(); // Use um ID válido para a jornada

mockPointModel.findById.mockReturnValueOnce({
exec: jest.fn().mockResolvedValue(null),
});

await expect(
service.addJourneyToPoint(pointId, journeyId),
).rejects.toThrow(NotFoundException);
expect(mockPointModel.findById).toHaveBeenCalledWith(pointId);
});
});

describe('updateOrder', () => {
it('should perform bulk updates and return the result', async () => {
const id1 = new Types.ObjectId();
const id2 = new Types.ObjectId();

const journeys: UpdatePointInterface[] = [
{
_id: id1.toHexString(),
order: 1,
name: 'Point A',
__v: 0,
createdAt: '',
updatedAt: '',
},
{
_id: id2.toHexString(),
order: 2,
name: 'Point B',
__v: 0,
createdAt: '',
updatedAt: '',
},
];

const bulkOperations = journeys.map((trail) => ({
updateOne: {
filter: { _id: new Types.ObjectId(trail._id) },
update: { $set: { order: trail.order } },
},
}));

const result = { modifiedCount: 2, matchedCount: 2 };
mockPointModel.bulkWrite.mockResolvedValue(result);

const response = await service.updateOrder(journeys);

expect(mockPointModel.bulkWrite).toHaveBeenCalledWith(bulkOperations);
expect(response).toEqual(result);
});
});
});

0 comments on commit b9e3fe5

Please sign in to comment.