Skip to content

Commit

Permalink
[TM-1271] Spec out the controller.
Browse files Browse the repository at this point in the history
  • Loading branch information
roguenet committed Sep 16, 2024
1 parent 6ba380f commit 172b4d3
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 5 deletions.
30 changes: 27 additions & 3 deletions apps/user-service/src/auth/auth.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,42 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { createMock, DeepMocked } from '@golevelup/ts-jest';
import { UnauthorizedException } from '@nestjs/common';

describe('AuthController', () => {
let controller: AuthController;
let authService: DeepMocked<AuthService>;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AuthController],
providers: [
{ provide: AuthService, useValue: authService = createMock<AuthService>() },
],
}).compile();

controller = module.get<AuthController>(AuthController);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});
afterEach(() => {
jest.restoreAllMocks();
})

it('should throw if creds are invalid', async () => {
authService.login.mockResolvedValue(null);

await expect(() => controller.login({ emailAddress: '[email protected]', password: 'asdfasdfasdf' }))
.rejects
.toThrow(UnauthorizedException)
})

it('returns a token if creds are valid', async () => {
const token = 'fake jwt token';
const userId = 123;
authService.login.mockResolvedValue({ token, userId })

const result = await controller.login({ emailAddress: '[email protected]', password: 'asdfasdfasdf' });
expect(result).toEqual({ type: 'logins', token, id: `${userId}` })
})
});
2 changes: 1 addition & 1 deletion apps/user-service/src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ describe('AuthService', () => {
it('should update the last logged in date on the user', async () => {
const user = await UserFactory.create({ password: 'fakepasswordhash' });
jest.spyOn(bcrypt, 'compare').mockImplementation(() => Promise.resolve(true));
jwtService.signAsync.mockReturnValue(Promise.resolve('fake jwt token'));
jwtService.signAsync.mockResolvedValue('fake jwt token');

await service.login(user.emailAddress, 'fakepassword');

Expand Down
13 changes: 12 additions & 1 deletion jest.preset.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
const nxPreset = require('@nx/jest/preset').default;

module.exports = { ...nxPreset };
module.exports = {
...nxPreset,

coverageThreshold: {
global: {
branches: 85,
functions: 95,
lines: 95,
statements: 95,
}
}
}

0 comments on commit 172b4d3

Please sign in to comment.