33// the real fetch abort path without depending on Azure latency.
44import { createServer , type Server } from "node:http" ;
55import type { AddressInfo } from "node:net" ;
6+ import { clearTimeout as clearRealTimeout , setTimeout as setRealTimeout } from "node:timers" ;
67import { afterEach , describe , expect , it , vi } from "vitest" ;
78import { listAzureSpeechVoices } from "./tts.js" ;
89
@@ -39,8 +40,13 @@ describe("listAzureSpeechVoices timeout", () => {
3940 { timeout : 2_000 } ,
4041 async ( ) => {
4142 let requestCount = 0 ;
42- const server = createServer ( ( _req , _res ) => {
43+ let notifyRequest = ( ) => { } ;
44+ const requestReceived = new Promise < void > ( ( resolve ) => {
45+ notifyRequest = resolve ;
46+ } ) ;
47+ const server = createServer ( ( _request , _response ) => {
4348 requestCount += 1 ;
49+ notifyRequest ( ) ;
4450 } ) ;
4551
4652 const port = await listenLocal ( server ) ;
@@ -56,26 +62,32 @@ describe("listAzureSpeechVoices timeout", () => {
5662 ) ;
5763
5864 const startedAt = Date . now ( ) ;
59- let watchdog : ReturnType < typeof setTimeout > | undefined ;
65+ let watchdog : ReturnType < typeof setRealTimeout > | undefined ;
6066
6167 try {
62- await expect (
63- Promise . race ( [
64- listAzureSpeechVoices ( {
65- apiKey : "not-a-real" ,
66- baseUrl : "https://custom.example.com" ,
67- timeoutMs : 100 ,
68- } ) ,
69- new Promise < never > ( ( _ , reject ) => {
70- watchdog = setTimeout ( ( ) => reject ( new Error ( "voices list did not time out" ) ) , 1_000 ) ;
71- } ) ,
72- ] ) ,
73- ) . rejects . toThrow ( / a b o r t e d | t i m e o u t | t i m e d o u t / i) ;
74- expect ( Date . now ( ) - startedAt ) . toBeLessThan ( 1_000 ) ;
68+ vi . useFakeTimers ( { toFake : [ "setTimeout" , "clearTimeout" ] } ) ;
69+ const watchdogPromise = new Promise < never > ( ( _ , reject ) => {
70+ watchdog = setRealTimeout ( ( ) => reject ( new Error ( "voices list did not time out" ) ) , 1_000 ) ;
71+ } ) ;
72+ const request = Promise . race ( [
73+ listAzureSpeechVoices ( {
74+ apiKey : "not-a-real" ,
75+ baseUrl : "https://custom.example.com" ,
76+ timeoutMs : 100 ,
77+ } ) ,
78+ watchdogPromise ,
79+ ] ) ;
80+ const rejection = expect ( request ) . rejects . toThrow ( / a b o r t e d | t i m e o u t | t i m e d o u t / i) ;
81+
82+ await Promise . race ( [ requestReceived , watchdogPromise ] ) ;
7583 expect ( requestCount ) . toBe ( 1 ) ;
84+ await vi . advanceTimersByTimeAsync ( 100 ) ;
85+ await rejection ;
86+ expect ( Date . now ( ) - startedAt ) . toBeLessThan ( 1_000 ) ;
7687 } finally {
88+ vi . useRealTimers ( ) ;
7789 if ( watchdog ) {
78- clearTimeout ( watchdog ) ;
90+ clearRealTimeout ( watchdog ) ;
7991 }
8092 await closeServer ( server ) ;
8193 }
0 commit comments