1+ import { Test , TestingModule } from '@nestjs/testing' ;
2+ import { AuthService } from './auth.service' ;
3+ import { UserService } from '../users/users.service' ;
4+ import { JwtService } from '@nestjs/jwt' ;
5+ import * as bcrypt from 'bcrypt' ;
6+ import { UnauthorizedException } from '@nestjs/common/exceptions' ;
7+
8+
9+ const mockUser = {
10+ email : 'test@example.com' ,
11+ _id : '12345' ,
12+ password : 'mockAccessToken' , // Hashing the password
13+ } ;
14+ const authServiceResult = {
15+ access_token : 'mockAccessToken' , // Hashing the password
16+ } ;
17+
18+ describe ( 'AuthService' , ( ) => {
19+ let authService : AuthService ;
20+ let userService : UserService ;
21+ let jwtService : JwtService ;
22+
23+ beforeEach ( async ( ) => {
24+ const module : TestingModule = await Test . createTestingModule ( {
25+ providers : [
26+ AuthService ,
27+ {
28+ provide : AuthService ,
29+ useValue : {
30+ signIn : jest . fn ( ) . mockResolvedValueOnce ( authServiceResult )
31+ . mockRejectedValueOnce ( new UnauthorizedException ( ) ) , // Error scenario
32+ }
33+ } ,
34+ {
35+ provide : UserService ,
36+ useValue : {
37+ findOneUser : jest . fn ( ) . mockResolvedValue ( authServiceResult )
38+ }
39+ } ,
40+ {
41+ provide : JwtService ,
42+ useValue : {
43+ compare : jest . fn ( ) . mockRejectedValue ( false ) ,
44+ signAsync : jest . fn ( ) . mockResolvedValue ( true )
45+ }
46+ }
47+
48+ ] ,
49+ } ) . compile ( ) ;
50+
51+ authService = module . get < AuthService > ( AuthService ) ;
52+ userService = module . get < UserService > ( UserService ) ;
53+ jwtService = module . get < JwtService > ( JwtService ) ;
54+ } ) ;
55+
56+ it ( 'should sign in a user and return an access token' , async ( ) => {
57+
58+ jest . spyOn ( userService , 'findOneUser' ) . mockResolvedValue ( mockUser ) ;
59+ jest . spyOn ( bcrypt , 'compare' ) . mockResolvedValue ( true ) ;
60+ jest . spyOn ( jwtService , 'signAsync' ) . mockResolvedValue ( 'access_token' ) ;
61+
62+ const result = await authService . signIn ( 'test@example.com' , 'password' ) ;
63+
64+ expect ( result ) . toBeDefined ( ) ;
65+ } ) ;
66+
67+ it ( 'should throw UnauthorizedException when passwords do not match' , async ( ) => {
68+ const hashedPassword = await bcrypt . hash ( 'password' , 10 ) ;
69+ const mockUser = {
70+ email : 'test@example.com' ,
71+ _id : '12345' ,
72+ password : hashedPassword ,
73+ } ;
74+
75+ jest . spyOn ( userService , 'findOneUser' ) . mockResolvedValue ( mockUser ) ;
76+ jest . spyOn ( bcrypt , 'compare' ) . mockResolvedValue ( false ) ; // Passwords do not match
77+ } ) ;
78+ } ) ;
0 commit comments