All files / test/mocks baileys.ts

92.85% Statements 13/14
100% Branches 0/0
85.71% Functions 6/7
92.3% Lines 12/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                                          7x 7x 3x 3x             3x 3x 3x     7x     4x   4x             7x   3x      
import { vi } from "vitest";
 
export type MockBaileysSocket = {
	ev: import("events").EventEmitter;
	ws: { close: ReturnType<typeof vi.fn> };
	sendPresenceUpdate: ReturnType<typeof vi.fn>;
	sendMessage: ReturnType<typeof vi.fn>;
	user?: { id?: string };
};
 
export type MockBaileysModule = {
	DisconnectReason: { loggedOut: number };
	fetchLatestBaileysVersion: ReturnType<typeof vi.fn>;
	makeCacheableSignalKeyStore: ReturnType<typeof vi.fn>;
	makeWASocket: ReturnType<typeof vi.fn>;
	useMultiFileAuthState: ReturnType<typeof vi.fn>;
	jidToE164?: (jid: string) => string | null;
	proto?: unknown;
};
 
export function createMockBaileys(): { mod: MockBaileysModule; lastSocket: () => MockBaileysSocket } {
	const sockets: MockBaileysSocket[] = [];
	const makeWASocket = vi.fn((opts: unknown) => {
		const ev = new (require("events").EventEmitter)();
		const sock: MockBaileysSocket = {
			ev,
			ws: { close: vi.fn() },
			sendPresenceUpdate: vi.fn().mockResolvedValue(undefined),
			sendMessage: vi.fn().mockResolvedValue({ key: { id: "msg123" } }),
			user: { id: "123@s.whatsapp.net" },
		};
		setImmediate(() => ev.emit("connection.update", { connection: "open" }));
		sockets.push(sock);
		return sock;
	});
 
	const mod: MockBaileysModule = {
		DisconnectReason: { loggedOut: 401 },
		fetchLatestBaileysVersion: vi.fn().mockResolvedValue({ version: [1, 2, 3] }),
		makeCacheableSignalKeyStore: vi.fn((keys: unknown) => keys),
		makeWASocket,
		useMultiFileAuthState: vi.fn(async () => ({
			state: { creds: {}, keys: {} },
			saveCreds: vi.fn(),
		})),
		jidToE164: (jid: string) => jid.replace(/@.*$/, "").replace(/^/, "+"),
	};
 
	return {
		mod,
		lastSocket: () => sockets[sockets.length - 1]!,
	};
}