import MediumAuth from '../src/auth';
import * as fs from 'fs';
import * as path from 'path';
// Mock environment variables
process.env.MEDIUM_CLIENT_ID = 'test_client_id';
process.env.MEDIUM_CLIENT_SECRET = 'test_client_secret';
process.env.MEDIUM_ACCESS_TOKEN = 'test_access_token';
describe('MediumAuth', () => {
let auth: MediumAuth;
const tokenFilePath = path.join(process.cwd(), '.medium-tokens.json');
beforeEach(() => {
// Clean up any existing token files
if (fs.existsSync(tokenFilePath)) {
fs.unlinkSync(tokenFilePath);
}
});
afterEach(() => {
// Clean up after tests
if (fs.existsSync(tokenFilePath)) {
fs.unlinkSync(tokenFilePath);
}
});
describe('constructor', () => {
it('should initialize with valid credentials', () => {
expect(() => {
auth = new MediumAuth();
}).not.toThrow();
});
it('should throw error when CLIENT_ID is missing', () => {
delete process.env.MEDIUM_CLIENT_ID;
expect(() => {
new MediumAuth();
}).toThrow('Missing MEDIUM_CLIENT_ID');
process.env.MEDIUM_CLIENT_ID = 'test_client_id';
});
it('should throw error when CLIENT_SECRET is missing', () => {
delete process.env.MEDIUM_CLIENT_SECRET;
expect(() => {
new MediumAuth();
}).toThrow('Missing MEDIUM_CLIENT_SECRET');
process.env.MEDIUM_CLIENT_SECRET = 'test_client_secret';
});
});
describe('authenticate', () => {
beforeEach(() => {
auth = new MediumAuth();
});
it('should authenticate with direct access token', async () => {
await expect(auth.authenticate()).resolves.not.toThrow();
expect(auth.isAuthenticated()).toBe(true);
});
it('should save tokens to file', async () => {
await auth.authenticate();
expect(fs.existsSync(tokenFilePath)).toBe(true);
const tokenData = JSON.parse(fs.readFileSync(tokenFilePath, 'utf-8'));
expect(tokenData.access_token).toBe('test_access_token');
});
});
describe('getAccessToken', () => {
beforeEach(() => {
auth = new MediumAuth();
});
it('should return access token after authentication', async () => {
await auth.authenticate();
const token = auth.getAccessToken();
expect(token).toBe('test_access_token');
});
it('should throw error if not authenticated', () => {
expect(() => {
auth.getAccessToken();
}).toThrow('Authentication Required');
});
});
describe('clearTokens', () => {
beforeEach(async () => {
auth = new MediumAuth();
await auth.authenticate();
});
it('should clear tokens and delete token file', () => {
auth.clearTokens();
expect(fs.existsSync(tokenFilePath)).toBe(false);
expect(auth.isAuthenticated()).toBe(false);
});
});
});