85 lines
2.4 KiB
TypeScript
85 lines
2.4 KiB
TypeScript
import { ExecutionContext } from "@nestjs/common";
|
|
import { ConfigService } from "@nestjs/config";
|
|
import { Test, TestingModule } from "@nestjs/testing";
|
|
import { getIronSession } from "iron-session";
|
|
import { JwtService } from "../../crypto/services/jwt.service";
|
|
import { OptionalAuthGuard } from "./optional-auth.guard";
|
|
|
|
jest.mock("jose", () => ({}));
|
|
jest.mock("iron-session", () => ({
|
|
getIronSession: jest.fn(),
|
|
}));
|
|
|
|
describe("OptionalAuthGuard", () => {
|
|
let guard: OptionalAuthGuard;
|
|
let _jwtService: JwtService;
|
|
|
|
const mockJwtService = {
|
|
verifyJwt: jest.fn(),
|
|
};
|
|
|
|
const mockConfigService = {
|
|
get: jest.fn().mockReturnValue("session-password"),
|
|
};
|
|
|
|
beforeEach(async () => {
|
|
const module: TestingModule = await Test.createTestingModule({
|
|
providers: [
|
|
OptionalAuthGuard,
|
|
{ provide: JwtService, useValue: mockJwtService },
|
|
{ provide: ConfigService, useValue: mockConfigService },
|
|
],
|
|
}).compile();
|
|
|
|
guard = module.get<OptionalAuthGuard>(OptionalAuthGuard);
|
|
_jwtService = module.get<JwtService>(JwtService);
|
|
});
|
|
|
|
it("should return true and set user for valid token", async () => {
|
|
const request = { user: null };
|
|
const context = {
|
|
switchToHttp: () => ({
|
|
getRequest: () => request,
|
|
getResponse: () => ({}),
|
|
}),
|
|
} as unknown as ExecutionContext;
|
|
|
|
(getIronSession as jest.Mock).mockResolvedValue({ accessToken: "valid" });
|
|
mockJwtService.verifyJwt.mockResolvedValue({ sub: "u1" });
|
|
|
|
const result = await guard.canActivate(context);
|
|
expect(result).toBe(true);
|
|
expect(request.user).toEqual({ sub: "u1" });
|
|
});
|
|
|
|
it("should return true if no token", async () => {
|
|
const context = {
|
|
switchToHttp: () => ({
|
|
getRequest: () => ({}),
|
|
getResponse: () => ({}),
|
|
}),
|
|
} as ExecutionContext;
|
|
|
|
(getIronSession as jest.Mock).mockResolvedValue({});
|
|
|
|
const result = await guard.canActivate(context);
|
|
expect(result).toBe(true);
|
|
});
|
|
|
|
it("should return true even if token invalid", async () => {
|
|
const context = {
|
|
switchToHttp: () => ({
|
|
getRequest: () => ({ user: null }),
|
|
getResponse: () => ({}),
|
|
}),
|
|
} as ExecutionContext;
|
|
|
|
(getIronSession as jest.Mock).mockResolvedValue({ accessToken: "invalid" });
|
|
mockJwtService.verifyJwt.mockRejectedValue(new Error("invalid"));
|
|
|
|
const result = await guard.canActivate(context);
|
|
expect(result).toBe(true);
|
|
expect(context.switchToHttp().getRequest().user).toBeNull();
|
|
});
|
|
});
|