Skip to content

Commit

Permalink
test: Add auth unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
Yu-Rou-Weng committed May 31, 2024
1 parent 9d1403f commit 400fcc6
Show file tree
Hide file tree
Showing 2 changed files with 121 additions and 0 deletions.
115 changes: 115 additions & 0 deletions src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';
import { JwtService } from '@nestjs/jwt';
import { IUserRepository } from 'src/users/user.interface';
import { mockAuthRepository } from '../mockRepositories/mockAuthRepo';
import { BadRequestException, InternalServerErrorException } from '@nestjs/common';

describe('AuthService', () => {
let authService: AuthService;
let jwtService: any;

beforeEach(async () => {
jwtService = {
sign: jest.fn().mockReturnValue('fake_token'),
};

const module: TestingModule = await Test.createTestingModule({
providers: [
AuthService,
{
provide: IUserRepository,
useValue: mockAuthRepository
},
{
provide: JwtService,
useValue: jwtService
},
],
}).compile();

authService = module.get<AuthService>(AuthService);
});

afterEach(() => {
jest.clearAllMocks();
});

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

describe('generateJwt', () => {
it('Generate a JWT for a valid payload', () => {
const payload = { sub: '1', email: 'emily@gmail.com', name: 'Emily', exp: 3600 };
const token = authService.generateJwt(payload);
expect(token).toEqual('fake_token');
expect(jwtService.sign).toHaveBeenCalledWith(payload);
});
});

describe('signIn', () => {
const userReq = { id: '1', email: 'test@gmail.com', name: 'Test User' };
it('Throw BadRequestException if no user provided', async () => {
await expect(authService.signIn(null)).rejects.toThrow(BadRequestException);
});

it('Register a new user if not found', async () => {
mockAuthRepository.findOneByCondition.mockResolvedValueOnce(null);
mockAuthRepository.create.mockReturnValue(userReq);
mockAuthRepository.save.mockResolvedValue({ ...userReq, id: '1' });

const result = await authService.signIn(userReq);
expect(result).toEqual('fake_token');
expect(mockAuthRepository.create).toHaveBeenCalledWith(userReq);
expect(mockAuthRepository.save).toHaveBeenCalled();
});

it('Log in existing user', async () => {
mockAuthRepository.findOneByCondition.mockResolvedValue(userReq);

const result = await authService.signIn(userReq);
expect(result).toEqual('fake_token');
expect(mockAuthRepository.findOneByCondition).toHaveBeenCalledWith({ where: { email: userReq.email } });
});
});

describe('registerUser', () => {
it('Successfully register new user', async () => {
const userReq = { id: '2', email: 'new@gmail.com', name: 'New User' };
mockAuthRepository.create.mockReturnValue(userReq);
mockAuthRepository.save.mockResolvedValue({ ...userReq, id: '2' });

const result = await authService.registerUser(userReq);
expect(result).toEqual('fake_token');
expect(mockAuthRepository.create).toHaveBeenCalledWith(userReq);
expect(mockAuthRepository.save).toHaveBeenCalled();
});

it('Throw InternalServerErrorException on save error', async () => {
const userReq = { id: '3', email: 'error@gmail.com', name: 'Error User' };
mockAuthRepository.create.mockReturnValue(userReq);
mockAuthRepository.save.mockRejectedValue(new Error('DB error'));

await expect(authService.registerUser(userReq)).rejects.toThrow(InternalServerErrorException);
});
});

describe('findUserByEmail', () => {
it('Return a user if found', async () => {
const user = { id: '3', email: 'exist@gmail.com', name: 'Exist User' };
mockAuthRepository.findOneByCondition.mockResolvedValue(user);

const result = await authService.findUserByEmail('exist@gmail.com');
expect(result).toEqual(user);
expect(mockAuthRepository.findOneByCondition).toHaveBeenCalledWith({ where: { email: 'exist@gmail.com' } });
});

it('Return null if user not found', async () => {
mockAuthRepository.findOneByCondition.mockResolvedValue(null);

const result = await authService.findUserByEmail('NoExist@gmail.com');
expect(result).toBeNull();
});
});
});
6 changes: 6 additions & 0 deletions src/mockRepositories/mockAuthRepo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const mockAuthRepository = {
findOne: jest.fn(),
create: jest.fn(),
save: jest.fn(),
findOneByCondition: jest.fn(),
};

0 comments on commit 400fcc6

Please sign in to comment.