Open History to see the last commit
1import { execFile } from 'node:child_process'
2import { promisify } from 'node:util'
3import { fileURLToPath } from 'node:url'
4import { expect, test } from 'vitest'
5β
6const execFileAsync = promisify(execFile)
7const preload = fileURLToPath(new URL('../mock-api.mjs', import.meta.url))
8β
9test('independent Node processes mock the API with networking disabled', async () => {
10 const script = `
11 const { Socket } = await import('node:net')
12 Socket.prototype.connect = () => { throw new Error('Network disabled') }
13 const posts = await fetch('https://jsonplaceholder.typicode.com/posts').then(r => r.json())
14 const user = await fetch('https://jsonplaceholder.typicode.com/users/1').then(r => r.json())
15 const invalid = await fetch('https://jsonplaceholder.typicode.com/posts/invalid')
16 const missing = await fetch('https://jsonplaceholder.typicode.com/posts/999')
17 console.log(JSON.stringify({ post: posts[0].id, user: user.id, invalid: invalid.status, missing: await missing.text() }))
18 `
19 const results = await Promise.all(
20 [0, 1].map(() =>
21 execFileAsync(process.execPath, ['--import', preload, '--eval', script]),
22 ),
23 )
24 for (const result of results) {
25 expect(JSON.parse(result.stdout)).toEqual({
26 post: 1,
27 user: 1,
28 invalid: 404,
29 missing: '',
30 })
31 }
32})
33β
34test('unhandled API requests fail without reaching the network', async () => {
35 const script = `
36 const { Socket } = await import('node:net')
37 let connections = 0
38 Socket.prototype.connect = () => { connections++; throw new Error('Network disabled') }
39 try {
40 await fetch('https://jsonplaceholder.typicode.com/unhandled')
41 process.exitCode = 1
42 } catch {
43 console.log(JSON.stringify({ connections }))
44 }
45 `
46 const result = await execFileAsync(process.execPath, [
47 '--import',
48 preload,
49 '--eval',
50 script,
51 ])
52 expect(JSON.parse(result.stdout)).toEqual({ connections: 0 })
53})