Skip to content

Commit

Permalink
test: optimize the code according to the suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
a20688392 committed Aug 31, 2023
1 parent 7f8912e commit a3f71c3
Show file tree
Hide file tree
Showing 6 changed files with 219 additions and 317 deletions.
99 changes: 40 additions & 59 deletions src/auth/auth.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { type HttpException, ConflictException } from "@nestjs/common";
import { ConflictException } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { JwtModule } from "@nestjs/jwt";
import { PassportModule } from "@nestjs/passport";
Expand Down Expand Up @@ -57,55 +57,55 @@ describe("AuthController", () => {
});

describe("create", () => {
const createUserDto: CreateUserDto = {
account: "account",
email: "[email protected]",
name: "displayname",
password: "Password@123",
};
let mockedAuthService: jest.SpyInstance;

beforeEach(async () => {
mockedAuthService = jest.spyOn(authService, "register");
});

it("應該會創建一個使用者,並返回 201 狀態碼", async () => {
const createUserDto: CreateUserDto = {
account: "account",
email: "[email protected]",
name: "displayname",
password: "Password@123",
};
const expectedResponse: CreateUserResponse = {
message: "創建成功",
statusCode: 201,
};

jest.spyOn(authService, "register").mockResolvedValue(expectedResponse);
mockedAuthService.mockResolvedValue(expectedResponse);

const result = await authController.register(createUserDto);

expect(result).toEqual(expectedResponse);
});

it("應該會發生資料使用者重覆,並返回 409 狀態碼", async () => {
const createUserDto1: CreateUserDto = {
account: "account1",
email: "[email protected]",
name: "displayname",
password: "Password@123",
};

await authService.register(createUserDto1);
await authService
.register(createUserDto1)
.catch((error: HttpException) => {
expect(error).toBeInstanceOf(ConflictException);
expect(error.getResponse()).toEqual({
error: "Conflict",
message: ["email 已被註冊。", "account 已被註冊。"],
statusCode: 409,
});
await authService.register(createUserDto);
await authService.register(createUserDto).catch(error => {
expect(error).toBeInstanceOf(ConflictException);
expect((error as ConflictException).getResponse()).toEqual({
error: "Conflict",
message: ["email 已被註冊。", "account 已被註冊。"],
statusCode: 409,
});
});
});
});

it("should return access, refresh token and 201 http code when account information is correct.", async () => {
const request: Request = {
user: {
id: 1,
} as JwtUser,
} as unknown as Request;

const fakeAccessToken = "mocked_access_token";
const fakeRefreshToken = "mocked_refresh_token";

describe("login and refresh", () => {
const request: Request = {
user: {
id: 1,
} as JwtUser,
} as unknown as Request;
const fakeAccessToken = "mocked_access_token";
const fakeRefreshToken = "mocked_refresh_token";
let mockedAuthService: jest.SpyInstance;

beforeEach(async () => {
jest
.spyOn(authService, "generateAccessToken")
.mockReturnValue(Promise.resolve(fakeAccessToken));
Expand All @@ -114,12 +114,13 @@ describe("AuthController", () => {
.spyOn(authService, "generateRefreshToken")
.mockReturnValue(Promise.resolve(fakeRefreshToken));

const mockAuthService = jest.spyOn(authService, "sign");
mockedAuthService = jest.spyOn(authService, "sign");
});

it("should return access, refresh token and 201 http code when account information is correct.", async () => {
const result = await authController.login(request);

expect(mockAuthService).toHaveBeenCalledWith(request.user);

expect(mockedAuthService).toHaveBeenCalledWith(request.user);
const expectedResponse: GenerateTokenResponse = {
accessToken: fakeAccessToken,
refreshToken: fakeRefreshToken,
Expand All @@ -130,29 +131,9 @@ describe("AuthController", () => {
});

it("should return access, refresh token and 201 http code when refresh token is correct.", async () => {
const request: Request = {
user: {
id: 1,
} as JwtUser,
} as unknown as Request;

const fakeAccessToken = "mocked_access_token";
const fakeRefreshToken = "mocked_refresh_token";

jest
.spyOn(authService, "generateAccessToken")
.mockReturnValue(Promise.resolve(fakeAccessToken));

jest
.spyOn(authService, "generateRefreshToken")
.mockReturnValue(Promise.resolve(fakeRefreshToken));

const mockAuthService = jest.spyOn(authService, "sign");

const result = await authController.refresh(request);

expect(mockAuthService).toHaveBeenCalledWith(request.user);

expect(mockedAuthService).toHaveBeenCalledWith(request.user);
const expectedResponse: GenerateTokenResponse = {
accessToken: fakeAccessToken,
refreshToken: fakeRefreshToken,
Expand Down
155 changes: 61 additions & 94 deletions src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import {
type HttpException,
ConflictException,
HttpStatus,
} from "@nestjs/common";
import { ConflictException, HttpStatus } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { JwtModule } from "@nestjs/jwt";
import { PassportModule } from "@nestjs/passport";
Expand Down Expand Up @@ -57,13 +53,27 @@ describe("AuthService", () => {
});

describe("createUser - Data", () => {
const rawUser: CreateUserDto = {
account: "account1",
email: "[email protected]",
name: "displayname",
password: "Password@123",
};
const rawUserConflictEmail: CreateUserDto = {
account: "account2",
email: "[email protected]",
name: "displayname",
password: "Password@123",
};

const rawUserConflictAccount: CreateUserDto = {
account: "account",
email: "[email protected]",
name: "displayname",
password: "Password@123",
};

it("應該會創建 一個使用者", async () => {
const rawUser: CreateUserDto = {
account: "account1",
email: "[email protected]",
name: "displayname",
password: "Password@123",
};
const user = await authService.register(rawUser);

expect(user).toBeDefined();
Expand All @@ -72,46 +82,25 @@ describe("AuthService", () => {
});

it("應該會發生 email、account 已被註冊衝突", async () => {
const createUserDto1: CreateUserDto = {
account: "account",
email: "[email protected]",
name: "displayname",
password: "Password@123",
};

await authService.register(createUserDto1);
await authService
.register(createUserDto1)
.catch((error: HttpException) => {
expect(error).toBeInstanceOf(ConflictException);
expect(error.getResponse()).toEqual({
error: "Conflict",
message: ["email 已被註冊。", "account 已被註冊。"],
statusCode: 409,
});
await authService.register(rawUser);
await authService.register(rawUser).catch(error => {
expect(error).toBeInstanceOf(ConflictException);
expect((error as ConflictException).getResponse()).toEqual({
error: "Conflict",
message: ["email 已被註冊。", "account 已被註冊。"],
statusCode: 409,
});
});
});

it("應該會發生 email 已被註冊衝突", async () => {
const rawUser1: CreateUserDto = {
account: "account1",
email: "[email protected]",
name: "displayname",
password: "Password@123",
};
const rawUser2: CreateUserDto = {
account: "account2",
email: "[email protected]",
name: "displayname",
password: "Password@123",
};
const errors = await validate(rawUser1);
const errors = await validate(rawUser);

expect(errors.length).toBe(0);
await authService.register(rawUser1);
await authService.register(rawUser2).catch((error: HttpException) => {
await authService.register(rawUser);
await authService.register(rawUserConflictEmail).catch(error => {
expect(error).toBeInstanceOf(ConflictException);
expect(error.getResponse()).toEqual({
expect((error as ConflictException).getResponse()).toEqual({
error: "Conflict",
message: ["email 已被註冊。"],
statusCode: 409,
Expand All @@ -120,25 +109,13 @@ describe("AuthService", () => {
});

it("應該會發生 account 已被註冊衝突", async () => {
const rawUser1: CreateUserDto = {
account: "account",
email: "[email protected]",
name: "displayname",
password: "Password@123",
};
const rawUser2: CreateUserDto = {
account: "account",
email: "[email protected]",
name: "displayname",
password: "Password@123",
};
const errors = await validate(rawUser1);
const errors = await validate(rawUser);

expect(errors.length).toBe(0);
await authService.register(rawUser1);
await authService.register(rawUser2).catch((error: HttpException) => {
await authService.register(rawUser);
await authService.register(rawUserConflictAccount).catch(error => {
expect(error).toBeInstanceOf(ConflictException);
expect(error.getResponse()).toEqual({
expect((error as ConflictException).getResponse()).toEqual({
error: "Conflict",
message: ["account 已被註冊。"],
statusCode: 409,
Expand All @@ -148,24 +125,33 @@ describe("AuthService", () => {
});

describe("user local login", () => {
it("should be login successfully.", async () => {
const mockUser = {
email: "[email protected]",
id: 1,
};
const fakeAccessToken = "mocked_access_token";
const fakeRefreshToken = "mocked_refresh_token";
const expectedStatusCode = HttpStatus.CREATED;

const fakeAccessToken = "mocked_access_token";
const fakeRefreshToken = "mocked_refresh_token";
const mockUser: Partial<UserEntity> = {
account: "test",
email: "[email protected]",
id: 1,
name: "test",
password: "$2b$05$zc4SaUDmE68OgrabgSoLX.CDMHZ8SD/aDeuJc7rxKmtqjP5WpH.Me",
};
const mockJwtUser: JwtUser = {
id: 1,
};

beforeEach(async () => {
jest
.spyOn(authService, "generateAccessToken")
.mockReturnValue(Promise.resolve(fakeAccessToken));

jest
.spyOn(authService, "generateRefreshToken")
.mockReturnValue(Promise.resolve(fakeRefreshToken));
});

it("should be login successfully.", async () => {
const expectedStatusCode = HttpStatus.CREATED;

const result = await authService.sign(mockUser);
const result = await authService.sign(mockJwtUser);

expect(result).toEqual({
accessToken: fakeAccessToken,
Expand All @@ -177,14 +163,6 @@ describe("AuthService", () => {
it("should be validate successfully.", async () => {
const mockAccount = "test";
const mockPassword = "Password@123";
const mockUser: Partial<UserEntity> = {
account: "test",
email: "[email protected]",
id: 1,
name: "test",
password:
"$2b$05$zc4SaUDmE68OgrabgSoLX.CDMHZ8SD/aDeuJc7rxKmtqjP5WpH.Me",
};

jest
.spyOn(userService, "findOne")
Expand Down Expand Up @@ -213,14 +191,6 @@ describe("AuthService", () => {
it("when the account exist but password not correct should be validate failure.", async () => {
const mockAccount = "test";
const mockPassword = "Password@1234";
const mockUser: Partial<UserEntity> = {
account: "test",
email: "[email protected]",
id: 1,
name: "test",
password:
"$2b$05$zc4SaUDmE68OgrabgSoLX.CDMHZ8SD/aDeuJc7rxKmtqjP5WpH.Me",
};

jest
.spyOn(userService, "findOne")
Expand All @@ -234,21 +204,18 @@ describe("AuthService", () => {
});

describe("generate Token", () => {
const userId = 1;
const payload: JwtUser = {
id: userId,
};

it("should generate access token", async () => {
const userId = 1;
const payload: JwtUser = {
id: userId,
};
const result = await authService.generateAccessToken(payload);

expect(result).toBeDefined();
});

it("should generate refresh token", async () => {
const userId = 1;
const payload: JwtUser = {
id: userId,
};
const result = await authService.generateRefreshToken(payload);

expect(result).toBeDefined();
Expand Down
Loading

0 comments on commit a3f71c3

Please sign in to comment.