blob: c9ace4de27725e06a6be3c7fff4ca1001f27b563 [file] [log] [blame]
import MockAdapter from 'axios-mock-adapter';
import { api, login, register, getUserInfo } from './auth';
describe('auth API', () => {
let mockAxios;
beforeEach(() => {
// 确保使用我们导出的 api 实例
mockAxios = new MockAdapter(api);
localStorage.clear();
});
afterEach(() => {
mockAxios.restore();
});
describe('login', () => {
it('should send login request with username and password', async () => {
const mockResponse = {
code: 200,
data: {
token: 'mock-token',
// 确保响应结构与实际API一致
userInfo: { username: 'testuser' }
},
message: '登录成功'
};
mockAxios.onPost('/user/login').reply(200, mockResponse);
const response = await login('testuser', 'testpass');
expect(response.data).toEqual(mockResponse);
// 检查token是否存入localStorage
expect(localStorage.getItem('token')).toBe('mock-token');
});
it('should handle login failure', async () => {
mockAxios.onPost('/user/login').reply(401);
await expect(login('wronguser', 'wrongpass')).rejects.toThrow();
});
});
describe('register', () => {
it('should send register request with username, password and code', async () => {
const mockResponse = {
code: 200,
message: '注册成功'
};
mockAxios.onPost('/user/regist').reply(200, mockResponse);
const response = await register('newuser', 'newpass', 'invite123');
expect(response.data).toEqual(mockResponse);
});
it('should handle registration failure', async () => {
mockAxios.onPost('/user/regist').reply(400);
await expect(register('newuser', 'newpass', 'wrongcode')).rejects.toThrow();
});
});
describe('getUserInfo', () => {
it('should send request with token to get user info', async () => {
const mockResponse = {
code: 200,
data: { username: 'testuser', role: 'user' }
};
mockAxios.onGet('/user/info').reply(200, mockResponse);
const response = await getUserInfo('test-token');
expect(response.data).toEqual(mockResponse);
});
it('should handle unauthorized request', async () => {
mockAxios.onGet('/user/info').reply(401);
await expect(getUserInfo('invalid-token')).rejects.toThrow();
});
});
describe('request interceptor', () => {
it('should add Authorization header when token exists', async () => {
localStorage.setItem('token', 'test-token');
const mockResponse = { data: 'success' };
mockAxios.onGet('/test').reply((config) => {
expect(config.headers.Authorization).toBe('Bearer test-token');
return [200, mockResponse];
});
const response = await api.get('/test');
expect(response.data).toEqual(mockResponse);
});
it('should not add Authorization header when token does not exist', async () => {
const mockResponse = { data: 'success' };
mockAxios.onGet('/test').reply((config) => {
expect(config.headers.Authorization).toBeUndefined();
return [200, mockResponse];
});
const response = await api.get('/test');
expect(response.data).toEqual(mockResponse);
});
});
});