oversci/__test__/services/file.test.ts
2025-01-31 19:32:50 +08:00

110 lines
2.8 KiB
TypeScript

// __tests__/services/file.test.ts
import { FileService } from "@/app/lib/services/file";
import axios from "axios";
// Mock axios
jest.mock("axios");
const mockedAxios = axios as jest.Mocked<typeof axios>;
describe("FileService", () => {
beforeEach(() => {
// 清除所有 mock 的数据
jest.clearAllMocks();
});
describe("getFileTree", () => {
it("should fetch file tree successfully", async () => {
const mockData = [
{
id: "1",
name: "测试文件夹",
type: "folder",
children: [
{
id: "2",
name: "测试文档.md",
type: "file",
},
],
},
];
mockedAxios.get.mockResolvedValueOnce({ data: mockData });
const result = await FileService.getFileTree();
expect(mockedAxios.get).toHaveBeenCalledWith("/api/files");
expect(result).toEqual(mockData);
});
it("should handle error when fetching file tree fails", async () => {
const error = new Error("Network error");
mockedAxios.get.mockRejectedValueOnce(error);
await expect(FileService.getFileTree()).rejects.toThrow("Network error");
});
});
describe("createFile", () => {
it("should create file successfully", async () => {
const newFile = {
name: "新文档.md",
type: "file" as const,
parentId: "1",
};
const mockResponse = {
id: "3",
...newFile,
createdAt: new Date().toISOString(),
};
mockedAxios.post.mockResolvedValueOnce({ data: mockResponse });
const result = await FileService.createFile(newFile);
expect(mockedAxios.post).toHaveBeenCalledWith("/api/files", newFile);
expect(result).toEqual(mockResponse);
});
});
describe("updateFile", () => {
it("should update file successfully", async () => {
const updateData = {
id: "2",
name: "重命名文档.md",
};
const mockResponse = {
...updateData,
type: "file",
updatedAt: new Date().toISOString(),
};
mockedAxios.put.mockResolvedValueOnce({ data: mockResponse });
const result = await FileService.updateFile(updateData);
expect(mockedAxios.put).toHaveBeenCalledWith(
`/api/files/${updateData.id}`,
updateData
);
expect(result).toEqual(mockResponse);
});
});
describe("deleteFile", () => {
it("should delete file successfully", async () => {
const fileId = "2";
const mockResponse = { success: true };
mockedAxios.delete.mockResolvedValueOnce({ data: mockResponse });
const result = await FileService.deleteFile(fileId);
expect(mockedAxios.delete).toHaveBeenCalledWith(`/api/files/${fileId}`);
expect(result).toEqual(mockResponse);
});
});
});