Files
RedditBot/tests/browser-client.test.ts
T

64 lines
2.9 KiB
TypeScript

import { describe, expect, it, vi } from 'vitest';
import type { BrowserContext, Page } from 'playwright';
import { BrowserClient, type BrowserRuntime } from '../src/browser/client.js';
import type { Logger } from '../src/utils/logger.js';
import { getTestConfig } from './testUtils.js';
function createLogger(): Logger {
return { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } as unknown as Logger;
}
describe('BrowserClient', () => {
it('launches only the managed headless Playwright context', async () => {
const context = { pages: () => [] } as unknown as BrowserContext;
const runtime: BrowserRuntime = { launchPersistentContext: vi.fn().mockResolvedValue(context) };
const client = new BrowserClient(getTestConfig(), createLogger(), runtime);
await expect(client.initialize()).resolves.toBe(context);
expect(runtime.launchPersistentContext).toHaveBeenCalledWith(
expect.stringContaining('browser-session'),
expect.objectContaining({ headless: true }),
);
});
it('adds an imported session without logging cookie values', async () => {
const addCookies = vi.fn().mockResolvedValue(undefined);
const context = { pages: () => [], addCookies } as unknown as BrowserContext;
const runtime: BrowserRuntime = { launchPersistentContext: vi.fn().mockResolvedValue(context) };
const logger = createLogger();
const client = new BrowserClient(getTestConfig(), logger, runtime);
const cookies = [{ name: 'reddit_session', value: 'secret', domain: '.reddit.com', path: '/', expires: -1, httpOnly: true, secure: true, sameSite: 'Lax' as const }];
await client.importRedditCookies(cookies);
expect(addCookies).toHaveBeenCalledWith(cookies);
expect(client.getSessionState()).toBe('unknown');
expect(JSON.stringify(logger)).not.toContain('secret');
});
it('reads the username and stable account ID from Reddit\'s nested me.json response', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ kind: 't2', data: { name: 'bot-account', id: 'abc123' } }),
});
vi.stubGlobal('fetch', fetchMock);
const page = {
evaluate: async (pageFunction: () => Promise<string | null>) => pageFunction(),
} as unknown as Page;
const context = { pages: () => [page] } as unknown as BrowserContext;
const runtime: BrowserRuntime = { launchPersistentContext: vi.fn().mockResolvedValue(context) };
const client = new BrowserClient(getTestConfig(), createLogger(), runtime);
await expect(client.getAuthenticatedUsername()).resolves.toBe('bot-account');
await expect(client.getAuthenticatedIdentity()).resolves.toEqual({
username: 'bot-account',
accountId: 't2_abc123',
});
expect(fetchMock).toHaveBeenCalledWith(
'https://www.reddit.com/api/me.json',
{ credentials: 'include' },
);
vi.unstubAllGlobals();
});
});