Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 39 additions & 3 deletions extensions/cli/src/telemetry/posthogService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import os from "node:os";
import path from "node:path";

import { machineIdSync } from "node-machine-id";
import { vi, describe, it, beforeEach, afterEach, expect } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

// Mock the auth module and node-machine-id
vi.mock("../auth/workos.js", () => ({
Expand All @@ -21,9 +21,14 @@ vi.mock("node-machine-id", () => {
};
});

// Import after mocks are set up
import { loadAuthConfig, isAuthenticatedConfig } from "../auth/workos.js";
// Mock dns/promises for connection checks
vi.mock("dns/promises", () => {
const lookup = vi.fn();
return { default: { lookup } };
});

// eslint-disable-next-line import/order
import { isAuthenticatedConfig, loadAuthConfig } from "../auth/workos.js";
import { PosthogService } from "./posthogService.js";

describe("PosthogService", () => {
Expand Down Expand Up @@ -117,4 +122,35 @@ describe("PosthogService", () => {
expect(service.isEnabled).toBe(false);
});
});

describe("hasInternetConnection and offline client", () => {
let service: PosthogService;

beforeEach(() => {
service = new PosthogService();
});

it("returns false on DNS error, caches and refetches", async () => {
const dns: any = (await import("dns/promises")).default;
dns.lookup.mockRejectedValueOnce(new Error("offline"));
const first = await (service as any).hasInternetConnection();
expect(first).toBe(false);
dns.lookup.mockResolvedValueOnce({
address: "1.1.1.1",
family: 4,
} as any);
await (service as any).hasInternetConnection();
const second = (service as any)._hasInternetConnection;
expect(second).toBe(true);
expect(dns.lookup).toHaveBeenCalledTimes(2);
});

it("getClient returns undefined when offline", async () => {
const dns: any = (await import("dns/promises")).default;
dns.lookup.mockRejectedValueOnce(new Error("offline"));
const client = await (service as any).getClient();
expect(client).toBeUndefined();
expect(dns.lookup).toHaveBeenCalledTimes(1);
});
});
});
Loading