Skip to content

Include Unit Test for Event Service. #46

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
135 changes: 134 additions & 1 deletion src/events/events.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,63 @@
import { Test, TestingModule } from '@nestjs/testing';
import { EventService } from './events.users.service';
import { getModelToken } from '@nestjs/mongoose';
import { NotFoundException } from '@nestjs/common';
import { Types } from 'mongoose';
import { EventDto } from './dto/event.dto';
import { UpdateEventDto } from './dto/updateEvent.dto';
import { JoinMethod, Location, Status } from 'src/shared/interfaces/event.type';
import { TestModule } from 'src/shared/testkits';

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

const mockEvent = {
_id: new Types.ObjectId(),
title: 'Sample Event',
shortDesc: 'A short description',
description: 'A detailed description of the event',
host: 'Host Name',
coHost: ['Co-host One', 'Co-host Two'],
location: Location.PHYSICAL,
photo: 'https://example.com/photo.jpg',
joinMethod: JoinMethod.MEET,
link: 'https://example.com/event',
socialsLinks: {
linkedIn: 'https://linkedin.com/in/sample',
twitter: 'https://twitter.com/sample',
facebook: 'https://facebook.com/sample',
},
eventDate: new Date()
};

let eventModelMock = {
create: jest.fn().mockResolvedValue(mockEvent),
findById: jest.fn().mockImplementationOnce(() => ({
lean: jest.fn().mockReturnThis(),
exec: jest.fn().mockResolvedValue(mockEvent),
})),
findByIdAndUpdate: jest.fn().mockImplementationOnce(() => ({
lean: jest.fn().mockReturnThis(),
exec: jest.fn().mockResolvedValue(mockEvent),
})),
countDocuments: jest.fn(),
find: jest.fn().mockImplementationOnce(() => ({
lean: jest.fn().mockReturnThis(),
exec: jest.fn().mockResolvedValue(mockEvent),
})),
};


beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [TestModule],
providers: [EventService],
providers: [
EventService,
{
provide: getModelToken(Event.name),
useValue: eventModelMock,
},
],
}).compile();

service = module.get<EventService>(EventService);
Expand All @@ -17,4 +66,88 @@ describe('EventService', () => {
it('should be defined', () => {
expect(service).toBeDefined();
});

describe('createEvent', () => {
it('should create and return an event', async () => {
const eventDto: EventDto = {
title: 'Sample Event',
shortDesc: 'Short description',
description: 'Event description',
host: 'Host',
coHost: ['Co-host 1', 'Co-host 2'],
location: Location.ONLINE,
photo: 'photo_url',
joinMethod: JoinMethod.MEET,
link: 'event_link',
socialsLinks: { linkedIn: 'linkedin_url', twitter: 'twitter_url', facebook: 'facebook_url' },
eventDate: new Date(),
};

const result = await service.createEvent(eventDto);
expect(eventModelMock.create).toHaveBeenCalledWith(eventDto);
expect(result).toEqual(mockEvent);
});
});

describe('findById', () => {
it('should return an event by ID', async () => {
const result = await service.findById(mockEvent._id.toString());
expect(result).toEqual(mockEvent);
expect(eventModelMock.findById).toHaveBeenCalledWith(mockEvent._id.toString());
});

it('should throw NotFoundException if event is not found', async () => {
eventModelMock.findById.mockImplementationOnce(() => ({
lean: jest.fn().mockReturnThis(),
exec: jest.fn().mockResolvedValue(null)}));
await expect(service.findById('12345')).rejects.toThrow(NotFoundException);
});
});

describe('updateEvent', () => {
it('should update and return an event', async () => {
const updateEventDto: UpdateEventDto = { title: 'Updated Event' };
eventModelMock.findByIdAndUpdate.mockResolvedValue(mockEvent);
const result = await service.updateEvent(mockEvent._id.toString(), updateEventDto);
expect(result).toEqual(mockEvent);
expect(eventModelMock.findByIdAndUpdate).toHaveBeenCalledWith(mockEvent._id.toString(), updateEventDto, { new: true, lean: true });
});

it('should throw NotFoundException if event to update is not found', async () => {
eventModelMock.findByIdAndUpdate.mockImplementationOnce(() => ({
lean: jest.fn().mockReturnThis(),
exec: jest.fn().mockResolvedValue(null)}));
await expect(service.updateEvent('12345', {})).rejects.toThrow(NotFoundException);
});
});

describe('softDeleteEvent', () => {
it('should soft delete an event', async () => {
eventModelMock.findByIdAndUpdate.mockResolvedValue(mockEvent);
const result = await service.softDeleteEvent(mockEvent._id.toString());
expect(result).toEqual(mockEvent);
expect(eventModelMock.findByIdAndUpdate).toHaveBeenCalledWith(mockEvent._id.toString(), { status: Status.DELETED }, { new: true });
});

it('should throw NotFoundException if event to delete is not found', async () => {
let id = mockEvent._id.toString();
eventModelMock.findByIdAndUpdate.mockRejectedValueOnce(new NotFoundException(`Event with ID ${id} not found`));
await expect(service.softDeleteEvent(id)).rejects.toThrow(new NotFoundException(`Event with ID ${id} not found`));
});
});

describe('approveEvent', () => {
it('should approve an event', async () => {
eventModelMock.findByIdAndUpdate.mockResolvedValue(mockEvent);
const result = await service.approveEvent(mockEvent._id.toString());
expect(result).toEqual(mockEvent);
expect(eventModelMock.findByIdAndUpdate).toHaveBeenCalledWith(mockEvent._id.toString(), { status: Status.APPROVED }, { new: true });
});

it('should throw NotFoundException if event to approve is not found', async () => {
let id = mockEvent._id.toString();
eventModelMock.findByIdAndUpdate.mockRejectedValueOnce(new NotFoundException(`Event with ID ${id} not found`));
await expect(service.approveEvent(id)).rejects.toThrow(new NotFoundException(`Event with ID ${id} not found`));
});
});
});
4 changes: 3 additions & 1 deletion src/events/events.users.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import { EventAdminsController } from './events.admin.controller';
import { DBModule } from 'src/shared/schema';

@Module({
imports: [DBModule],
imports: [
DBModule
],
controllers: [EventUserController, EventAdminsController],
providers: [EventService],
exports: [EventService],
Expand Down
3 changes: 2 additions & 1 deletion src/events/events.users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ import { ApiReq } from 'src/shared/interfaces/req.type';
import { getPagingParams, getPaginated } from 'src/shared/utils';
import { UpdateEventDto } from './dto/updateEvent.dto';
import { Status } from 'src/shared/interfaces/event.type';
import { InjectModel } from '@nestjs/mongoose';

@Injectable()
export class EventService {
constructor(
@Inject(Event.name)
@InjectModel(Event.name)
private readonly eventModel: Model<EventDocument>,
) {}

Expand Down
2 changes: 2 additions & 0 deletions src/shared/interfaces/event.type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ export enum JoinMethod {
TWITTER = 'TWITTER',
}


export enum Status {
APPROVED = 'APPROVED',
PENDING = 'PENDING',
DELETED = 'DELETED',
ACTIVE = "ACTIVE"
}

export type SocialsLinks = {
Expand Down