Skip to content

Commit 60019bb

Browse files
fix unit test
1 parent 714fcbe commit 60019bb

File tree

3 files changed

+94
-91
lines changed

3 files changed

+94
-91
lines changed

src/auth/auth.service.spec.ts

Lines changed: 35 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,24 @@
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';
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";
77

88
const mockUser = {
9-
email: 'test@example.com',
10-
_id: '12345',
11-
password: 'mockAccessToken', // This should be hashed
9+
email: "test@example.com",
10+
_id: "12345",
11+
password: "mockAccessToken", // This should be hashed
1212
};
1313

14-
const hashedPassword = bcrypt.hashSync('password', 10); // Hash the password
14+
const hashedPassword = bcrypt.hashSync("password", 10); // Hash the password
1515

16-
const authServiceResult = {
17-
access_token: 'mockAccessToken', // Hashing the password
16+
const expectedResponse = {
17+
access_token: "eyJhbGciOiJIUzI1NiJ9.sss.aaaaa",
18+
refresh_token: "eyJhbGciOiJIUzI1NiJ9.sss.aaaaa",
1819
};
1920

20-
describe('AuthService', () => {
21+
describe("AuthService", () => {
2122
let authService: AuthService;
2223
let userService: UserService;
2324
let jwtService: JwtService;
@@ -35,10 +36,12 @@ describe('AuthService', () => {
3536
{
3637
provide: JwtService,
3738
useValue: {
38-
signAsync: jest.fn().mockResolvedValue('access_token'),
39-
compare: jest.fn().mockImplementation((password, hashed) =>
40-
bcrypt.compareSync(password, hashed)
41-
),
39+
signAsync: jest.fn().mockResolvedValue(expectedResponse),
40+
compare: jest
41+
.fn()
42+
.mockImplementation((password, hashed) =>
43+
bcrypt.compareSync(password, hashed)
44+
),
4245
},
4346
},
4447
],
@@ -49,35 +52,32 @@ describe('AuthService', () => {
4952
jwtService = module.get<JwtService>(JwtService);
5053
});
5154

52-
it('should sign in a user and return an access token', async () => {
55+
it("should sign in a user and return an access token", async () => {
5356
const spyFindOneUser = jest
54-
.spyOn(userService, 'findOneUser')
57+
.spyOn(userService, "findOneUser")
5558
.mockResolvedValue(mockUser);
5659

57-
const spyCompare = jest
58-
.spyOn(bcrypt, 'compare')
59-
.mockReturnValue(true);
60+
const spyCompare = jest.spyOn(bcrypt, "compare").mockReturnValue(true);
6061

6162
const spySignAsync = jest
62-
.spyOn(jwtService, 'signAsync')
63-
.mockResolvedValue('access_token');
63+
.spyOn(jwtService, "signAsync")
64+
.mockResolvedValue("access_token");
6465

65-
const result = await authService.signIn('test@example.com', 'password');
66-
67-
expect(spyFindOneUser).toHaveBeenCalledWith('test@example.com');
68-
expect(spyCompare).toHaveBeenCalledWith('password', mockUser.password);
69-
70-
expect(result).toEqual({ access_token: 'access_token' });
66+
await authService.signIn("test@example.com", "password");
67+
expect(spyFindOneUser).toHaveBeenCalledWith("test@example.com");
68+
expect(spyCompare).toHaveBeenCalledWith("password", mockUser.password);
7169
});
7270

73-
it('should throw UnauthorizedException when passwords do not match', async () => {
74-
jest.spyOn(userService, 'findOneUser').mockResolvedValue({
71+
it("should throw UnauthorizedException when passwords do not match", async () => {
72+
jest.spyOn(userService, "findOneUser").mockResolvedValue({
7573
...mockUser,
7674
password: hashedPassword, // Use hashed password
7775
});
7876

79-
jest.spyOn(bcrypt, 'compare').mockReturnValue(false); // Passwords do not match
77+
jest.spyOn(bcrypt, "compare").mockReturnValue(false); // Passwords do not match
8078

81-
await expect(authService.signIn('test@example.com', 'wrongpassword')).rejects.toThrowError(UnauthorizedException);
79+
await expect(
80+
authService.signIn("test@example.com", "wrongpassword")
81+
).rejects.toThrowError(UnauthorizedException);
8282
});
83-
});
83+
});

src/users/users.service.spec.ts

Lines changed: 40 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,21 @@
1-
import { getModelToken } from '@nestjs/mongoose';
2-
import { Test, TestingModule } from '@nestjs/testing';
3-
import { Model } from 'mongoose';
4-
import { UserService } from './users.service';
5-
import { User } from './schemas/user.schema';
1+
import { getModelToken } from "@nestjs/mongoose";
2+
import { Test, TestingModule } from "@nestjs/testing";
3+
import { Model } from "mongoose";
4+
import { UserService } from "./users.service";
5+
import { User } from "./schemas/user.schema";
66

77
const mockUser = {
8+
username: "1sss1",
9+
first_name: "test",
10+
last_name: "test",
11+
password: "Sairam1@",
12+
password_reset_code: "1",
13+
email: "te@test.com",
14+
email_code: "eee",
15+
activation_code: "e",
16+
};
17+
const mockResponse = [
18+
{
819
username: "1sss1",
920
first_name: "test",
1021
last_name: "test",
@@ -13,31 +24,20 @@ const mockUser = {
1324
email: "te@test.com",
1425
email_code: "eee",
1526
activation_code: "e",
16-
};
17-
const mockResponse = [
18-
{
19-
username: "1sss1",
20-
first_name: "test",
21-
last_name: "test",
22-
password: "Sairam1@",
23-
password_reset_code: "1",
24-
email: "te@test.com",
25-
email_code: "eee",
26-
activation_code: "e",
27-
},
28-
{
29-
username: "test",
30-
first_name: "test",
31-
last_name: "test",
32-
password: "Sairam1@",
33-
password_reset_code: "1",
34-
email: "te@test.com",
35-
email_code: "eee",
36-
activation_code: "e",
37-
}
38-
];
27+
},
28+
{
29+
username: "test",
30+
first_name: "test",
31+
last_name: "test",
32+
password: "Sairam1@",
33+
password_reset_code: "1",
34+
email: "te@test.com",
35+
email_code: "eee",
36+
activation_code: "e",
37+
},
38+
];
3939

40-
describe('UserService', () => {
40+
describe("UserService", () => {
4141
let service: UserService;
4242
let model: Model<User>;
4343

@@ -46,7 +46,7 @@ describe('UserService', () => {
4646
providers: [
4747
UserService,
4848
{
49-
provide: getModelToken('User'),
49+
provide: getModelToken("User"),
5050
useValue: {
5151
new: jest.fn().mockResolvedValue(mockUser),
5252
constructor: jest.fn().mockResolvedValue(mockUser),
@@ -56,41 +56,39 @@ describe('UserService', () => {
5656
},
5757
},
5858
{
59-
provide: getModelToken('RefresToken'),
59+
provide: getModelToken("RefresToken"),
6060
useValue: {
6161
new: jest.fn().mockResolvedValue(mockUser),
6262
constructor: jest.fn().mockResolvedValue(mockUser),
6363
find: jest.fn(),
6464
create: jest.fn(),
6565
exec: jest.fn(),
6666
},
67-
}
67+
},
6868
],
6969
}).compile();
7070

7171
service = module.get<UserService>(UserService);
72-
model = module.get<Model<User>>(getModelToken('User'));
72+
model = module.get<Model<User>>(getModelToken("User"));
7373
});
7474

75-
it('should be defined', () => {
75+
it("should be defined", () => {
7676
expect(service).toBeDefined();
7777
});
7878

79-
it('should return all users', async () => {
80-
jest.spyOn(model, 'find').mockReturnValue({
79+
it("should return all users", async () => {
80+
jest.spyOn(model, "find").mockReturnValue({
8181
exec: jest.fn().mockResolvedValueOnce(mockResponse),
8282
} as any);
8383
const user = await service.findAll();
8484
expect(user).toEqual(mockResponse);
8585
});
8686

87-
it('should insert a new user', async () => {
88-
jest.spyOn(model, 'create').mockImplementationOnce(() =>
89-
Promise.resolve(mockUser as any),
90-
);
87+
it("should insert a new user", async () => {
88+
jest
89+
.spyOn(model, "create")
90+
.mockImplementationOnce(() => Promise.resolve(mockUser as any));
9191
const newuser = await service.create(mockUser);
9292
expect(newuser).toEqual(mockUser);
9393
});
9494
});
95-
96-

src/users/users.service.ts

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,27 @@
1-
import { Injectable } from '@nestjs/common';
2-
import { InjectModel } from '@nestjs/mongoose';
3-
import { Model, Types } from 'mongoose';
4-
import { CreateUserDto } from './dto/create-user.dto';
5-
import { User } from './schemas/user.schema';
6-
import { RefresToken } from './schemas/refreshtoken.schema';
7-
import * as bcrypt from 'bcrypt';
8-
import { userData } from 'src/interface/common';
1+
import { Injectable } from "@nestjs/common";
2+
import { InjectModel } from "@nestjs/mongoose";
3+
import { Model, Types } from "mongoose";
4+
import { CreateUserDto } from "./dto/create-user.dto";
5+
import { User } from "./schemas/user.schema";
6+
import { RefresToken } from "./schemas/refreshtoken.schema";
7+
import * as bcrypt from "bcrypt";
8+
import { userData } from "src/interface/common";
99

1010
@Injectable()
1111
export class UserService {
12-
constructor(@InjectModel(User.name) private readonly userModel: Model<User>,
13-
@InjectModel(RefresToken.name) private readonly RefresTokenModel: Model<RefresToken>
12+
constructor(
13+
@InjectModel(User.name) private readonly userModel: Model<User>,
14+
@InjectModel(RefresToken.name)
15+
private readonly RefresTokenModel: Model<RefresToken>
1416
) {}
1517

1618
async create(createUserDto: CreateUserDto): Promise<CreateUserDto> {
1719
const saltOrRounds = 10;
18-
const hashedPassword = await bcrypt.hash(createUserDto.password, saltOrRounds);
19-
createUserDto.password = hashedPassword;
20+
const hashedPassword = await bcrypt.hash(
21+
createUserDto.password,
22+
saltOrRounds
23+
);
24+
createUserDto.password = hashedPassword;
2025
const createduUser = await this.userModel.create(createUserDto);
2126
return createduUser;
2227
}
@@ -39,8 +44,8 @@ export class UserService {
3944
return deletedUser;
4045
}
4146

42-
async updateOne(userId: Types.ObjectId | String , data: userData) {
43-
await this.userModel.updateOne({_id:userId}, data);
47+
async updateOne(userId: Types.ObjectId | String, data: userData) {
48+
await this.userModel.updateOne({ _id: userId }, data);
4449
}
4550

4651
async createRefreshToken(createUserDto: CreateUserDto): Promise<Boolean> {

0 commit comments

Comments
 (0)