| 1 | import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; |
| 2 | |
| 3 | import { ensureOrganization, isEnvironmentAuthConfig } from "./workos.js"; |
| 4 | |
| 5 | describe("ensureOrganization with API key org scope", () => { |
| 6 | const originalEnv = { ...process.env }; |
| 7 | const originalFetch = global.fetch; |
| 8 | |
| 9 | beforeEach(() => { |
| 10 | vi.restoreAllMocks(); |
| 11 | }); |
| 12 | |
| 13 | afterEach(() => { |
| 14 | process.env = { ...originalEnv }; |
| 15 | global.fetch = originalFetch as any; |
| 16 | }); |
| 17 | |
| 18 | it("resolves organizationId via auth/scope for API key auth", async () => { |
| 19 | const mockFetch = vi.fn().mockResolvedValue({ |
| 20 | ok: true, |
| 21 | json: async () => ({ organizationId: "org_123" }), |
| 22 | }); |
| 23 | (global as any).fetch = mockFetch; |
| 24 | |
| 25 | const envAuthConfig = { |
| 26 | accessToken: "sk_test_api_key", |
| 27 | organizationId: null as string | null, |
| 28 | } as const; |
| 29 | |
| 30 | const result = await ensureOrganization(envAuthConfig, true); |
| 31 | expect(result).not.toBeNull(); |
| 32 | if (result && isEnvironmentAuthConfig(result)) { |
| 33 | expect(result.organizationId).toBe("org_123"); |
| 34 | } else { |
| 35 | throw new Error("Expected environment auth config result"); |
| 36 | } |
| 37 | expect(mockFetch).toHaveBeenCalledOnce(); |
| 38 | }); |
| 39 | |
| 40 | it("keeps organizationId null if endpoint not available", async () => { |
| 41 | const mockFetch = vi.fn().mockResolvedValue({ ok: false }); |
| 42 | (global as any).fetch = mockFetch; |
| 43 | |
| 44 | const envAuthConfig = { |
| 45 | accessToken: "sk_test_api_key", |
| 46 | organizationId: null as string | null, |
| 47 | } as const; |
| 48 | |
| 49 | const result = await ensureOrganization(envAuthConfig, true); |
| 50 | expect(result).not.toBeNull(); |
| 51 | if (result && isEnvironmentAuthConfig(result)) { |
| 52 | expect(result.organizationId).toBeNull(); |
| 53 | } else { |
| 54 | throw new Error("Expected environment auth config result"); |
| 55 | } |
| 56 | expect(mockFetch).toHaveBeenCalledOnce(); |
| 57 | }); |
| 58 | }); |