Skip to content
5 changes: 5 additions & 0 deletions jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ const config: Config = {
'^src/(.*)$': '<rootDir>/$1',
'^@/(.*)$': '<rootDir>/$1',
'^test/(.*)$': '<rootDir>/../$1',
"^@/decorators/(.*)$": "<rootDir>/decorators/$1",
"^@/interceptors/(.*)$": "<rootDir>/interceptors/$1",
"^@/middlewares/(.*)$": "<rootDir>/middlewares/$1",
"^@/utils/(.*)$": "<rootDir>/utils/$1",
"^@/guards/(.*)$": "<rootDir>/guards/$1"
},
testEnvironment: 'node',
};
Expand Down
119 changes: 109 additions & 10 deletions src/users/users.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,126 @@
/* eslint-disable jest/no-conditional-expect */
import { Test, TestingModule } from '@nestjs/testing';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { ServerResponse } from '../utils';
import { PrismaService } from 'src/prisma/prisma.service';

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

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UsersController],
providers: [UsersService],
})
.useMocker((token) => {
if (token === PrismaService) {
return {};
}
})
.compile();
providers: [UsersService, PrismaService],
}).compile();

controller = module.get<UsersController>(UsersController);
service = module.get<UsersService>(UsersService);
});

it('should be defined', () => {
expect(controller).toBeDefined();
describe('store', () => {
it('should create a new user', async () => {
const userData = {
name: 'Test',
lastName: 'User',
phone: '123456789',
};
const response = new ServerResponse(201, 'Successfully created user');

jest.spyOn(service, 'store').mockResolvedValueOnce(undefined);

expect(await controller.store(userData)).toEqual(response);
});

it('should throw error if creation fails', async () => {
const body = {
name: 'Updated',
lastName: 'User',
phone: '987654321',
};
jest
.spyOn(service, 'store')
.mockRejectedValueOnce(new Error('Store failed'));
try {
await controller.store(body);
throw new Error('Expected update function to throw an error');
} catch (error: any) {
expect(error.response).toEqual('Error');
expect(error.status).toEqual(400);
}
});
});

describe('update', () => {
it('should update an existing user', async () => {
const userId = '1';
const userData = {
name: 'Updated',
lastName: 'User',
phone: '987654321',
};
const response = new ServerResponse(201, 'Successfully updated user');

jest.spyOn(service, 'update').mockResolvedValueOnce(undefined);

expect(await controller.update(userData, userId)).toEqual(response);
});

it('should throw error if update fails', async () => {
const id = '1';
const userData = {
name: 'Updated',
lastName: 'User',
phone: '987654321',
};
jest
.spyOn(service, 'update')
.mockRejectedValueOnce(new Error('Update failed'));
try {
await controller.update(userData, id);
throw new Error('Expected update function to throw an error');
} catch (error: any) {
expect(error.response).toEqual('Error');
expect(error.status).toEqual(400);
}
});
});

describe('selfUpdate', () => {
it('should update the own user', async () => {
const userId = '1';
const userData = {
name: 'Updated',
lastName: 'User',
phone: '987654321',
};
const req = { user: { userId } };
const response = new ServerResponse(201, 'Successfully updated');

jest.spyOn(service, 'update').mockResolvedValueOnce(undefined);

expect(await controller.selfUpdate(userData, req)).toEqual(response);
});

it('should throw error if update fails', async () => {
const userId = '1';
const userData = {
name: 'Updated',
lastName: 'User',
phone: '987654321',
};
const req = { user: { userId } };
jest
.spyOn(service, 'update')
.mockRejectedValueOnce(new Error('Update failed'));
try {
await controller.selfUpdate(userData, req);
throw new Error('Expected update function to throw an error');
} catch (error: any) {
expect(error.response).toEqual('Error');
expect(error.status).toEqual(400);
}
});
});
});
60 changes: 51 additions & 9 deletions src/users/users.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,65 @@ import { UsersService } from './users.service';
import { PrismaService } from 'src/prisma/prisma.service';

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

const mockPrismaService = {
user: {
create: jest.fn(),
update: jest.fn(),
},
};

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UsersService],
providers: [UsersService, PrismaService],
})
.useMocker((token) => {
if (token === PrismaService) {
return {};
}
})
.overrideProvider(PrismaService)
.useValue(mockPrismaService)
.compile();

service = module.get<UsersService>(UsersService);
userService = module.get<UsersService>(UsersService);
});

it('should be defined', () => {
expect(service).toBeDefined();
expect(userService).toBeDefined();
});

describe('store function', () => {
const userPayload = {
name: 'matheus',
lastName: 'silva',
phone: '44999998311',
};

it('shold call the store function 1 time', async () => {
userService.store(userPayload);
expect(mockPrismaService.user.create).toHaveBeenCalledTimes(1);
});

it('shold call the store function with the parameters', async () => {
userService.store(userPayload);
const data = {
...userPayload,
password: userPayload.phone,
login: userPayload.phone,
createdAt: new Date().toISOString(),
};
expect(mockPrismaService.user.create).toHaveBeenCalledWith({ data });
});
});

describe('update function', () => {
const id = 'user_id_test';
const body = {
name: 'Matheus',
lastName: 'Silva',
phone: '44999998311',
};

it('shuld call the store function 1 time', async () => {
userService.update(id, body);
expect(mockPrismaService.user.update).toHaveBeenCalledTimes(1);
});
});
});