File size: 1,587 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import type { FetchHandlerResult, ProxyServer } from '../proxy'
import { createProxyServer } from '../proxy'

export type FetchHandler = (
  request: Request
) => FetchHandlerResult | Promise<FetchHandlerResult>

export interface NextWorkerFixture {
  proxyPort: number
  onFetch: (testId: string, handler: FetchHandler) => void
  cleanupTest: (testId: string) => void
}

class NextWorkerFixtureImpl implements NextWorkerFixture {
  public proxyPort: number = 0
  private proxyServer: ProxyServer | null = null
  private proxyFetchMap = new Map<string, FetchHandler>()

  async setup(): Promise<void> {
    const server = await createProxyServer({
      onFetch: this.handleProxyFetch.bind(this),
    })

    this.proxyPort = server.port
    this.proxyServer = server
  }

  teardown(): void {
    if (this.proxyServer) {
      this.proxyServer.close()
      this.proxyServer = null
    }
  }

  cleanupTest(testId: string): void {
    this.proxyFetchMap.delete(testId)
  }

  onFetch(testId: string, handler: FetchHandler): void {
    this.proxyFetchMap.set(testId, handler)
  }

  private async handleProxyFetch(
    testId: string,
    request: Request
  ): Promise<FetchHandlerResult> {
    const handler = this.proxyFetchMap.get(testId)
    return handler?.(request)
  }
}

export async function applyNextWorkerFixture(
  use: (fixture: NextWorkerFixture) => Promise<void>
): Promise<void> {
  const fixture = new NextWorkerFixtureImpl()
  await fixture.setup()
  // eslint-disable-next-line react-hooks/rules-of-hooks -- not React.use()
  await use(fixture)
  fixture.teardown()
}