import { describe, it, expect, beforeEach, vi, type MockInstance } from 'vitest';
import { LibraryThingProvider } from '../../providers/librarything-provider.js';
import type { ServiceContext } from '../../service-context.js';
// Mock the ServiceHttpClient to prevent actual network requests
vi.mock('../../http-client.js', () => {
// Define mock class inside the factory
const MockHttpClient = class {
public fetch = vi.fn();
constructor() {}
};
return {
ServiceHttpClient: MockHttpClient,
};
});
describe('LibraryThingProvider', () => {
let provider: LibraryThingProvider;
let mockContext: ServiceContext;
let mockFetch: MockInstance;
beforeEach(() => {
vi.clearAllMocks();
provider = new LibraryThingProvider();
// Get the mock instance of fetch from the mocked class
// @ts-ignore - accessing private property for testing
mockFetch = (provider['client'] as any).fetch;
mockContext = {
env: {
LIBRARYTHING_API_KEY: {
get: vi.fn().mockResolvedValue('test-api-key'),
},
} as any,
logger: {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
} as any,
};
});
describe('isAvailable', () => {
it('should return true when API key is present', async () => {
const isAvailable = await provider.isAvailable(mockContext.env);
expect(isAvailable).toBe(true);
});
it('should return false when API key is missing', async () => {
mockContext.env.LIBRARYTHING_API_KEY = undefined as any;
const envWithNullKey = {
LIBRARYTHING_API_KEY: { get: vi.fn().mockResolvedValue(null) }
} as any;
expect(await provider.isAvailable(envWithNullKey)).toBe(false);
});
});
describe('fetchEditionVariants', () => {
it('should return empty array if API key is missing', async () => {
mockContext.env.LIBRARYTHING_API_KEY = { get: vi.fn().mockResolvedValue(null) } as any;
const result = await provider.fetchEditionVariants('9780547928227', mockContext);
expect(result).toEqual([]);
expect(mockContext.logger.error).toHaveBeenCalledWith(expect.stringContaining('not configured'));
});
it('should normalize and parse valid XML response correctly', async () => {
const xmlResponse = `