Skip to content

Instantly share code, notes, and snippets.

@pwmcintyre
Last active July 13, 2021 11:19
Show Gist options
  • Save pwmcintyre/3e9eb5d6cfa7d8915d4c3cea2d9fefa1 to your computer and use it in GitHub Desktop.
Save pwmcintyre/3e9eb5d6cfa7d8915d4c3cea2d9fefa1 to your computer and use it in GitHub Desktop.
promisify a NodeJS http createServer for testing
# create a test server with canned responses
const server: TestServer = new TestServer(new Response(500, payload), new Response(200, payload))

# wait for it to start
const url = await server.ready()

# use it
fetch(url).then(async res => console.log(await res.json()), console.error)
import http, { Server } from 'http'
export class Response {
constructor (
public readonly code: number,
public readonly payload: any
) {}
}
export class TestServer {
private readonly server: Server
private readonly url: Promise<string>
constructor (...responses: Response[]) {
if (responses == null) responses = [new Response(501, 'Not Implemented')]
let count = 0
const server = http.createServer((req, res) => {
const r = responses[(count++) % responses.length]
res.writeHead(r.code, { 'Content-Type': 'application/json' })
res.write(JSON.stringify(r.payload))
res.end()
})
const url: Promise<string> = new Promise((resolve, reject) => {
server.listen(0, function () {
const url = new URL('http://localhost')
const info = server.address()
if (info !== null && typeof info !== 'string' && info.port !== null) url.port = info.port.toString()
resolve(url.toString())
})
})
this.server = server
this.url = url
}
public async ready (): Promise<string> {
return await this.url
}
public close (): void {
this.server.close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment