-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
148 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,7 +4,7 @@ import { | |
HttpStatus, | ||
} from "@nestjs/common"; | ||
import { ConfigModule } from "@nestjs/config"; | ||
import { JwtModule, JwtService } from "@nestjs/jwt"; | ||
import { JwtModule } from "@nestjs/jwt"; | ||
import { PassportModule } from "@nestjs/passport"; | ||
import { type TestingModule, Test } from "@nestjs/testing"; | ||
import { getRepositoryToken, TypeOrmModule } from "@nestjs/typeorm"; | ||
|
@@ -17,6 +17,7 @@ import { UserService } from "src/user/user.service"; | |
import type { Repository } from "typeorm"; | ||
|
||
import { AuthService } from "./auth.service"; | ||
import { type JwtUser } from "./jwt/jwt.interface"; | ||
import { JwtAccessStrategy } from "./jwt/jwt-access.strategy"; | ||
import { LocalStrategy } from "./local/local.strategy"; | ||
|
||
|
@@ -25,8 +26,6 @@ describe("AuthService", () => { | |
let userService: UserService; | ||
let userRepository: Repository<UserEntity> | undefined; | ||
|
||
const fakeAccessToken = "mocked_access_token"; | ||
|
||
beforeEach(async () => { | ||
const module: TestingModule = await Test.createTestingModule({ | ||
imports: [ | ||
|
@@ -45,20 +44,13 @@ describe("AuthService", () => { | |
// 使用測試資料庫的 Repository | ||
useValue: UserEntity, | ||
}, | ||
{ | ||
provide: JwtService, | ||
useValue: { | ||
// 模擬JwtService中的方法 | ||
sign: jest.fn(), | ||
}, | ||
}, | ||
LocalStrategy, | ||
JwtAccessStrategy, | ||
], | ||
}).compile(); | ||
|
||
userService = module.get<UserService>(UserService); | ||
authService = module.get<AuthService>(AuthService); | ||
userService = module.get<UserService>(UserService); | ||
userRepository = module.get<Repository<UserEntity>>( | ||
getRepositoryToken(UserEntity), | ||
); | ||
|
@@ -161,16 +153,23 @@ describe("AuthService", () => { | |
email: "[email protected]", | ||
id: 1, | ||
}; | ||
const fakeAccessToken = "mocked_access_token"; | ||
const fakeRefreshToken = "mocked_refresh_token"; | ||
const expectedStatusCode = HttpStatus.CREATED; | ||
|
||
jest | ||
.spyOn(authService, "generateAccessToken") | ||
.mockImplementation(async () => fakeAccessToken); | ||
.mockReturnValue(Promise.resolve(fakeAccessToken)); | ||
|
||
jest | ||
.spyOn(authService, "generateRefreshToken") | ||
.mockReturnValue(Promise.resolve(fakeRefreshToken)); | ||
|
||
const result = await authService.login(mockUser); | ||
|
||
expect(result).toEqual({ | ||
accessToken: fakeAccessToken, | ||
refreshToken: fakeRefreshToken, | ||
statusCode: expectedStatusCode, | ||
}); | ||
}); | ||
|
@@ -234,6 +233,28 @@ describe("AuthService", () => { | |
}); | ||
}); | ||
|
||
describe("generate Token", () => { | ||
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(); | ||
}); | ||
}); | ||
|
||
afterEach(async () => { | ||
await userRepository?.clear(); | ||
}); | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
import { type ExecutionContext, UnauthorizedException } from "@nestjs/common"; | ||
import { ConfigModule, ConfigService } from "@nestjs/config"; | ||
import { JwtModule, JwtService } from "@nestjs/jwt"; | ||
import { PassportModule } from "@nestjs/passport"; | ||
import { Test } from "@nestjs/testing"; | ||
import jestConfig from "src/config/jest.config"; | ||
|
||
import { JwtRefreshGuard } from "./jwt-refresh.guard"; | ||
import { JwtRefreshStrategy } from "./jwt-refresh.strategy"; | ||
|
||
describe("JwtRefreshGuard", () => { | ||
let jwtRefreshGuard: JwtRefreshGuard; | ||
let jwtService: JwtService; | ||
let configService: ConfigService; | ||
|
||
beforeEach(async () => { | ||
jest.useFakeTimers(); | ||
const moduleRef = await Test.createTestingModule({ | ||
imports: [ | ||
ConfigModule.forRoot({ | ||
load: [jestConfig], | ||
}), | ||
PassportModule, | ||
JwtModule.register({}), | ||
], | ||
providers: [JwtRefreshGuard, JwtRefreshStrategy, JwtService], | ||
}).compile(); | ||
|
||
jwtRefreshGuard = moduleRef.get<JwtRefreshGuard>(JwtRefreshGuard); | ||
jwtService = moduleRef.get<JwtService>(JwtService); | ||
configService = moduleRef.get<ConfigService>(ConfigService); | ||
}); | ||
|
||
it("should be defined", () => { | ||
expect(jwtRefreshGuard).toBeDefined(); | ||
}); | ||
|
||
it("should return true for a valid JWT", async () => { | ||
const payload = { id: 1 }; | ||
const secret: string | undefined = configService.get("jwtSecret.refresh"); | ||
const token = jwtService.sign(payload, { | ||
expiresIn: "7d", | ||
secret, | ||
}); | ||
|
||
const response = {}; | ||
const context: ExecutionContext = { | ||
getRequest: () => ({ | ||
headers: { | ||
authorization: `bearer ${token}`, | ||
}, | ||
}), | ||
getResponse: () => response, | ||
switchToHttp: () => context, | ||
} as unknown as ExecutionContext; | ||
|
||
const canActivate = await jwtRefreshGuard.canActivate(context); | ||
|
||
expect(canActivate).toBe(true); | ||
}); | ||
|
||
it("should throw an error for an expired JWT", async () => { | ||
const secret: string | undefined = configService.get("jwtSecret.refresh"); | ||
const token = jwtService.sign( | ||
{ | ||
id: 1, | ||
}, | ||
{ | ||
expiresIn: "7d", | ||
secret, | ||
}, | ||
); | ||
|
||
jest.advanceTimersByTime(8 * 24 * 60 * 60 * 1000); | ||
|
||
const response = {}; | ||
const context: ExecutionContext = { | ||
getRequest: () => ({ | ||
headers: { | ||
authorization: `bearer ${token}`, | ||
}, | ||
}), | ||
getResponse: () => response, | ||
switchToHttp: () => context, | ||
} as unknown as ExecutionContext; | ||
|
||
try { | ||
await jwtRefreshGuard.canActivate(context); | ||
} catch (error) { | ||
expect(error).toBeInstanceOf(UnauthorizedException); | ||
} | ||
}); | ||
|
||
afterEach(async () => { | ||
jest.clearAllTimers(); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters