test(auth): Add tests for AuthService and Auth validations

This commit is contained in:
Yunxiao Xu
2026-02-11 19:34:19 -08:00
parent c222b33ba5
commit e3bc699c64
4 changed files with 247 additions and 15 deletions

View File

@@ -0,0 +1,60 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
import axios from "axios"
import { AuthService } from "./auth"
vi.mock("axios")
const mockedAxios = axios as jest.Mocked<typeof axios>
describe("AuthService", () => {
beforeEach(() => {
vi.clearAllMocks()
localStorage.clear()
})
it("successfully logs in and stores the token", async () => {
const mockResponse = {
data: {
access_token: "fake-jwt-token",
token_type: "bearer",
},
}
mockedAxios.post.mockResolvedValueOnce(mockResponse)
const result = await AuthService.login("test@example.com", "password123")
expect(mockedAxios.post).toHaveBeenCalledWith("/api/auth/login", expect.any(FormData))
expect(result.access_token).toBe("fake-jwt-token")
expect(localStorage.getItem("token")).toBe("fake-jwt-token")
})
it("handles login failure", async () => {
mockedAxios.post.mockRejectedValueOnce(new Error("Invalid credentials"))
await expect(AuthService.login("test@example.com", "wrong")).rejects.toThrow("Invalid credentials")
expect(localStorage.getItem("token")).toBeNull()
})
it("successfully registers a user", async () => {
const mockResponse = {
data: {
id: "user-123",
email: "test@example.com",
},
}
mockedAxios.post.mockResolvedValueOnce(mockResponse)
const result = await AuthService.register("test@example.com", "password123")
expect(mockedAxios.post).toHaveBeenCalledWith("/api/auth/register", {
email: "test@example.com",
password: "password123",
})
expect(result.email).toBe("test@example.com")
})
it("logs out and clears the token", () => {
localStorage.setItem("token", "some-token")
AuthService.logout()
expect(localStorage.getItem("token")).toBeNull()
})
})