blob: 8571fbc84e36b1a969b4d7d4e0fc0aba8790ab38 [file] [log] [blame]
// src/api/__tests__/chat.test.js
const axios = require('axios');
const MockAdapter = require('axios-mock-adapter');
const {
createChat,
deleteChat,
getChatsByUser,
getChatsBetweenUsers
} = require('../chat');
jest.mock('axios');
describe('Chat API Tests', () => {
beforeEach(() => {
jest.clearAllMocks();
});
test('createChat should post chat data', async () => {
const mockData = {
senderId: 1,
receiverId: 2,
content: 'Hello!',
talkTime: '2025-06-09T10:00:00'
};
const mockResponse = { data: { ...mockData, informationid: 101 } };
axios.post.mockResolvedValue(mockResponse);
const response = await createChat(mockData);
expect(axios.post).toHaveBeenCalledWith(
'http://localhost:8080/chat/create',
mockData
);
expect(response.data).toEqual(mockResponse.data);
});
test('deleteChat should send delete request', async () => {
axios.delete.mockResolvedValue({ data: '删除成功' });
const response = await deleteChat(101);
expect(axios.delete).toHaveBeenCalledWith('http://localhost:8080/chat/delete/101');
expect(response.data).toBe('删除成功');
});
test('getChatsByUser should fetch all chats for a user', async () => {
const userId = 1;
const mockData = { data: [{ senderId: 1, receiverId: 2, content: 'Hi' }] };
axios.get.mockResolvedValue(mockData);
const result = await getChatsByUser(userId);
expect(axios.get).toHaveBeenCalledWith(`http://localhost:8080/chat/user/${userId}`);
expect(result).toEqual(mockData.data);
});
test('getChatsBetweenUsers should fetch chats between two users', async () => {
const user1 = 1;
const user2 = 2;
const mockData = {
data: [{ senderId: 1, receiverId: 2, content: 'Hi there!' }]
};
axios.get.mockResolvedValue(mockData);
const result = await getChatsBetweenUsers(user1, user2);
expect(axios.get).toHaveBeenCalledWith('http://localhost:8080/chat/between', {
params: { user1, user2 }
});
expect(result).toEqual(mockData.data);
});
test('getChatsByUser should return [] on error', async () => {
axios.get.mockRejectedValue(new Error('Failed'));
const result = await getChatsByUser(1);
expect(result).toEqual([]);
});
test('getChatsBetweenUsers should return [] on error', async () => {
axios.get.mockRejectedValue(new Error('Failed'));
const result = await getChatsBetweenUsers(1, 2);
expect(result).toEqual([]);
});
});