@@ -3,7 +3,7 @@ import os from "node:os";
33import path from "node:path" ;
44
55import { machineIdSync } from "node-machine-id" ;
6- import { vi , describe , it , beforeEach , afterEach , expect } from "vitest" ;
6+ import { afterEach , beforeEach , describe , expect , it , vi } from "vitest" ;
77
88// Mock the auth module and node-machine-id
99vi . mock ( "../auth/workos.js" , ( ) => ( {
@@ -21,9 +21,14 @@ vi.mock("node-machine-id", () => {
2121 } ;
2222} ) ;
2323
24- // Import after mocks are set up
25- import { loadAuthConfig , isAuthenticatedConfig } from "../auth/workos.js" ;
24+ // Mock dns/promises for connection checks
25+ vi . mock ( "dns/promises" , ( ) => {
26+ const lookup = vi . fn ( ) ;
27+ return { default : { lookup } } ;
28+ } ) ;
2629
30+ // eslint-disable-next-line import/order
31+ import { isAuthenticatedConfig , loadAuthConfig } from "../auth/workos.js" ;
2732import { PosthogService } from "./posthogService.js" ;
2833
2934describe ( "PosthogService" , ( ) => {
@@ -117,4 +122,35 @@ describe("PosthogService", () => {
117122 expect ( service . isEnabled ) . toBe ( false ) ;
118123 } ) ;
119124 } ) ;
125+
126+ describe ( "hasInternetConnection and offline client" , ( ) => {
127+ let service : PosthogService ;
128+
129+ beforeEach ( ( ) => {
130+ service = new PosthogService ( ) ;
131+ } ) ;
132+
133+ it ( "returns false on DNS error, caches and refetches" , async ( ) => {
134+ const dns : any = ( await import ( "dns/promises" ) ) . default ;
135+ dns . lookup . mockRejectedValueOnce ( new Error ( "offline" ) ) ;
136+ const first = await ( service as any ) . hasInternetConnection ( ) ;
137+ expect ( first ) . toBe ( false ) ;
138+ dns . lookup . mockResolvedValueOnce ( {
139+ address : "1.1.1.1" ,
140+ family : 4 ,
141+ } as any ) ;
142+ await ( service as any ) . hasInternetConnection ( ) ;
143+ const second = ( service as any ) . _hasInternetConnection ;
144+ expect ( second ) . toBe ( true ) ;
145+ expect ( dns . lookup ) . toHaveBeenCalledTimes ( 2 ) ;
146+ } ) ;
147+
148+ it ( "getClient returns undefined when offline" , async ( ) => {
149+ const dns : any = ( await import ( "dns/promises" ) ) . default ;
150+ dns . lookup . mockRejectedValueOnce ( new Error ( "offline" ) ) ;
151+ const client = await ( service as any ) . getClient ( ) ;
152+ expect ( client ) . toBeUndefined ( ) ;
153+ expect ( dns . lookup ) . toHaveBeenCalledTimes ( 1 ) ;
154+ } ) ;
155+ } ) ;
120156} ) ;
0 commit comments