53 lines
1.7 KiB
JavaScript
53 lines
1.7 KiB
JavaScript
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
import { loginUser, logoutUser } from '../../src/services/auth.service.js';
|
|
import { User } from '../../src/models/User.js';
|
|
|
|
vi.mock('../../src/models/User.js');
|
|
global.fetch = vi.fn();
|
|
|
|
describe('Auth Service', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
});
|
|
|
|
describe('loginUser', () => {
|
|
it('should throw error for invalid API Key', async () => {
|
|
fetch.mockResolvedValue({ status: 401 });
|
|
await expect(loginUser('bad_key')).rejects.toThrow('Invalid API Key');
|
|
});
|
|
|
|
it('should return existing user if found', async () => {
|
|
fetch.mockResolvedValue({ status: 200 });
|
|
const mockUser = { wkApiKey: 'valid_key', _id: '123' };
|
|
User.findOne.mockResolvedValue(mockUser);
|
|
|
|
const result = await loginUser('valid_key');
|
|
expect(result).toEqual(mockUser);
|
|
expect(User.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('should create new user if not found', async () => {
|
|
fetch.mockResolvedValue({ status: 200 });
|
|
User.findOne.mockResolvedValue(null);
|
|
const newUser = { wkApiKey: 'valid_key', _id: 'new_id' };
|
|
User.create.mockResolvedValue(newUser);
|
|
|
|
const result = await loginUser('valid_key');
|
|
expect(result).toEqual(newUser);
|
|
expect(User.create).toHaveBeenCalledWith(expect.objectContaining({
|
|
wkApiKey: 'valid_key',
|
|
tokenVersion: 0
|
|
}));
|
|
});
|
|
});
|
|
|
|
describe('logoutUser', () => {
|
|
it('should increment token version', async () => {
|
|
User.findByIdAndUpdate.mockResolvedValue(true);
|
|
const result = await logoutUser('userId');
|
|
expect(User.findByIdAndUpdate).toHaveBeenCalledWith('userId', { $inc: { tokenVersion: 1 } });
|
|
expect(result).toBe(true);
|
|
});
|
|
});
|
|
});
|