Files
madbase/tests/integration/test-utils.ts

80 lines
2.7 KiB
TypeScript

export interface MockOptions {
env?: Record<string, string>;
supabase?: {
claims?: Record<string, any>;
dbResults?: Record<string, any>; // simplified for now
insertResult?: any;
};
fetch?: {
urlPattern: string;
response: any;
status?: number;
}[];
}
export function createMockedFunction(code: string, mocks: MockOptions = {}): string {
const envMock = mocks.env ? `
globalThis._env = ${JSON.stringify(mocks.env)};
` : 'globalThis._env = {};';
const supabaseMock = mocks.supabase ? `
const mockSupabase = {
auth: {
getClaims: async (token) => {
if (token && token !== "invalid") {
return { data: { claims: ${JSON.stringify(mocks.supabase?.claims || {})} }, error: null };
}
return { data: null, error: "Invalid token" };
}
},
from: (table) => {
return {
select: (cols) => ({
eq: (col, val) => ({
limit: (n) => ({
maybeSingle: async () => {
// Simple mock: return configured result or null
return { data: ${JSON.stringify(mocks.supabase?.dbResults || null)} };
}
}),
single: async () => {
return { data: ${JSON.stringify(mocks.supabase?.dbResults || null)} };
}
})
}),
insert: async (data) => ({ data: ${JSON.stringify(mocks.supabase?.insertResult || {})}, error: null })
};
}
};
globalThis.createClient = (url, key, options) => mockSupabase;
` : `
globalThis.createClient = () => ({
auth: { getClaims: async () => ({ data: { claims: {} }, error: null }) },
from: () => ({ select: () => ({ eq: () => ({ limit: () => ({ maybeSingle: async () => ({ data: null }) }) }) }) })
});
`;
const fetchMock = mocks.fetch ? `
globalThis.fetch = async (url, options) => {
${mocks.fetch.map(mock => `
if (url.includes("${mock.urlPattern}")) {
return {
ok: ${mock.status ? mock.status >= 200 && mock.status < 300 : 'true'},
status: ${mock.status || 200},
json: async () => (${JSON.stringify(mock.response)}),
text: async () => JSON.stringify(${JSON.stringify(mock.response)})
};
}
`).join('\n')}
return { ok: false, status: 404, text: async () => "Not Found" };
};
` : '';
return `
${envMock}
${supabaseMock}
${fetchMock}
${code}
`;
}