blob: 8571fbc84e36b1a969b4d7d4e0fc0aba8790ab38 [file] [log] [blame]
ym9233bf06b12025-06-09 18:18:51 +08001// src/api/__tests__/chat.test.js
2const axios = require('axios');
3const MockAdapter = require('axios-mock-adapter');
4const {
5 createChat,
6 deleteChat,
7 getChatsByUser,
8 getChatsBetweenUsers
9} = require('../chat');
10
11jest.mock('axios');
12
13describe('Chat API Tests', () => {
14 beforeEach(() => {
15 jest.clearAllMocks();
16 });
17
18 test('createChat should post chat data', async () => {
19 const mockData = {
20 senderId: 1,
21 receiverId: 2,
22 content: 'Hello!',
23 talkTime: '2025-06-09T10:00:00'
24 };
25 const mockResponse = { data: { ...mockData, informationid: 101 } };
26 axios.post.mockResolvedValue(mockResponse);
27
28 const response = await createChat(mockData);
29
30 expect(axios.post).toHaveBeenCalledWith(
31 'http://localhost:8080/chat/create',
32 mockData
33 );
34 expect(response.data).toEqual(mockResponse.data);
35 });
36
37 test('deleteChat should send delete request', async () => {
38 axios.delete.mockResolvedValue({ data: '删除成功' });
39
40 const response = await deleteChat(101);
41
42 expect(axios.delete).toHaveBeenCalledWith('http://localhost:8080/chat/delete/101');
43 expect(response.data).toBe('删除成功');
44 });
45
46 test('getChatsByUser should fetch all chats for a user', async () => {
47 const userId = 1;
48 const mockData = { data: [{ senderId: 1, receiverId: 2, content: 'Hi' }] };
49 axios.get.mockResolvedValue(mockData);
50
51 const result = await getChatsByUser(userId);
52
53 expect(axios.get).toHaveBeenCalledWith(`http://localhost:8080/chat/user/${userId}`);
54 expect(result).toEqual(mockData.data);
55 });
56
57 test('getChatsBetweenUsers should fetch chats between two users', async () => {
58 const user1 = 1;
59 const user2 = 2;
60 const mockData = {
61 data: [{ senderId: 1, receiverId: 2, content: 'Hi there!' }]
62 };
63 axios.get.mockResolvedValue(mockData);
64
65 const result = await getChatsBetweenUsers(user1, user2);
66
67 expect(axios.get).toHaveBeenCalledWith('http://localhost:8080/chat/between', {
68 params: { user1, user2 }
69 });
70 expect(result).toEqual(mockData.data);
71 });
72
73 test('getChatsByUser should return [] on error', async () => {
74 axios.get.mockRejectedValue(new Error('Failed'));
75 const result = await getChatsByUser(1);
76 expect(result).toEqual([]);
77 });
78
79 test('getChatsBetweenUsers should return [] on error', async () => {
80 axios.get.mockRejectedValue(new Error('Failed'));
81 const result = await getChatsBetweenUsers(1, 2);
82 expect(result).toEqual([]);
83 });
84});