chore: removes done callbacks in tests [CHORE-1870] (#1875)

## Checklist

Chore: removes done callback; prefer async

- [x] I have ensured my pull request is not behind the main or master
branch of the original repository.
- [x] I have rebased all commits where necessary so that reviewing this
pull request can be done without having to merge it first.
- [x] I have written a commit message that passes commitlint linting.
- [x] I have ensured that my code changes pass linting tests.
- [x] I have ensured that my code changes pass unit tests.
- [x] I have described my pull request and the reasons for code changes
along with context if necessary.

---------

Co-authored-by: jongleberry <jonathanrichardong@gmail.com>
Co-authored-by: Jeff Wainwright <jeffry@tuta.com>
This commit is contained in:
Jeff Wainwright
2025-05-08 00:06:19 -07:00
committed by GitHub
parent 61bf494594
commit 9057541332
9 changed files with 175 additions and 142 deletions

View File

@@ -1,28 +1,38 @@
'use strict'
const { describe, it } = require('node:test')
const request = require('supertest')
const assert = require('node:assert/strict')
const { once } = require('node:events')
const Koa = require('../..')
describe('app', () => {
// ignore test on Node.js v18
(/^v18\./.test(process.version) ? it.skip : it)('should handle socket errors', (t, done) => {
it('should handle socket errors', async () => {
const app = new Koa()
let errorCaught = false
app.use((ctx, next) => {
// triggers ctx.socket.writable == false
ctx.socket.emit('error', new Error('boom'))
app.use((ctx) => {
ctx.socket.destroy(new Error('boom'))
})
app.on('error', err => {
assert.strictEqual(err.message, 'boom')
done()
errorCaught = true
})
request(app.callback())
.get('/')
.end(() => {})
const server = app.listen()
try {
const req = require('http').get({
port: server.address().port
})
req.on('error', () => {})
const [err] = await once(app, 'error')
assert.strictEqual(err.message, 'boom')
assert.strictEqual(errorCaught, true)
} finally {
await server.close()
}
})
it('should set development env when NODE_ENV missing', () => {

View File

@@ -561,7 +561,8 @@ describe('app.respond', () => {
const app = new Koa()
app.use(async ctx => {
ctx.body = new Blob(['hello']).stream()
const blob = new Blob(['hello'])
ctx.body = blob.stream()
})
return request(app.callback())
@@ -727,21 +728,24 @@ describe('app.respond', () => {
})
describe('when an error occurs', () => {
it('should emit "error" on the app', (t, done) => {
it('should emit "error" on the app', async () => {
const app = new Koa()
app.use(ctx => {
throw new Error('boom')
})
let errorCaught = false
app.on('error', err => {
assert.strictEqual(err.message, 'boom')
done()
assert.strictEqual(err.message, 'test error')
errorCaught = true
})
request(app.callback())
app.use(ctx => {
throw new Error('test error')
})
await request(app.callback())
.get('/')
.end(() => {})
.expect(500)
assert.strictEqual(errorCaught, true)
})
describe('with an .expose property', () => {

View File

@@ -8,12 +8,16 @@ describe('ctx.assert(value, status)', () => {
it('should throw an error', () => {
const ctx = context()
let assertionRan = false
try {
ctx.assert(false, 404)
throw new Error('asdf')
ctx.assert(false, 404, 'custom message')
throw new Error('should not reach here')
} catch (err) {
assertionRan = true
assert.strictEqual(err.status, 404)
assert.strictEqual(err.message, 'custom message')
assert.strictEqual(err.expose, true)
}
assert(assertionRan)
})
})

View File

@@ -71,14 +71,13 @@ describe('ctx.onerror(err)', () => {
assert.strictEqual(Object.prototype.hasOwnProperty.call(res.headers, 'x-csrf-token'), false)
})
it('should ignore error after headerSent', (t, done) => {
it('should ignore error after headerSent', async () => {
const app = new Koa()
app.on('error', (err, { res }) => {
assert.strictEqual(err.message, 'mock error')
assert.strictEqual(err.headerSent, true)
res.end()
done()
})
app.use(async ctx => {
@@ -89,10 +88,10 @@ describe('ctx.onerror(err)', () => {
ctx.body = 'response'
})
request(app.callback())
await request(app.callback())
.get('/')
.expect('X-Foo', 'Bar')
.expect(200, () => {})
.expect(200)
})
it('should set status specified in the error using statusCode', () => {
@@ -236,22 +235,24 @@ describe('ctx.onerror(err)', () => {
assert.strictEqual(removed, 2)
})
it('should stringify error if it is an object', (t, done) => {
it('should stringify error if it is an object', async () => {
const app = new Koa()
app.on('error', err => {
let assertionRan = false
assert.strictEqual(err.message, 'non-error thrown: {"key":"value"}')
done()
assertionRan = true
assert(assertionRan, 'assertion was not executed')
})
app.use(async ctx => {
throw { key: 'value' } // eslint-disable-line no-throw-literal
})
request(app.callback())
await request(app.callback())
.get('/')
.expect(500)
.expect('Internal Server Error', () => {})
.expect('Internal Server Error')
})
})
})

View File

@@ -3,7 +3,7 @@
const { describe, it } = require('node:test')
const assert = require('node:assert/strict')
const Stream = require('stream')
const http = require('http')
const request = require('supertest')
const Koa = require('../../')
const context = require('../../test-helpers/context')
@@ -25,29 +25,17 @@ describe('ctx.href', () => {
assert.strictEqual(ctx.href, 'http://localhost/users/1?next=/dashboard')
})
it('should work with `GET http://example.com/foo`', (t, done) => {
it('should work with `GET http://example.com/foo`', async () => {
const app = new Koa()
app.use(ctx => {
ctx.body = ctx.href
})
app.listen(function () {
const server = this
const address = this.address()
http.get({
host: 'localhost',
path: 'http://example.com/foo',
port: address.port
}, res => {
assert.strictEqual(res.statusCode, 200)
let buf = ''
res.setEncoding('utf8')
res.on('data', s => { buf += s })
res.on('end', () => {
assert.strictEqual(buf, 'http://example.com/foo')
done()
server.close()
})
})
})
const res = await request(app.callback())
.get('/foo')
.set('Host', 'example.com')
.expect(200)
assert.strictEqual(res.text, 'http://example.com/foo')
})
})

View File

@@ -5,6 +5,7 @@ const request = require('supertest')
const assert = require('node:assert/strict')
const Koa = require('../..')
const http = require('http')
const { once } = require('node:events')
describe('ctx.flushHeaders()', () => {
it('should set headersSent', () => {
@@ -14,6 +15,7 @@ describe('ctx.flushHeaders()', () => {
ctx.body = 'Body'
ctx.status = 200
ctx.flushHeaders()
assert.strictEqual(ctx.headerSent, true)
assert.strictEqual(ctx.res.headersSent, true)
})
@@ -79,9 +81,11 @@ describe('ctx.flushHeaders()', () => {
assert.strictEqual(res.headers.vary, undefined, 'header set after flushHeaders')
})
it('should flush headers first and delay to send data', (t, done) => {
it('should flush headers first and delay to send data', async () => {
const PassThrough = require('stream').PassThrough
const app = new Koa()
let headersFlushed = false
let dataReceived = false
app.use(ctx => {
ctx.type = 'json'
@@ -89,36 +93,44 @@ describe('ctx.flushHeaders()', () => {
ctx.headers.Link = '</css/mycss.css>; as=style; rel=preload, <https://img.craftflair.com>; rel=preconnect; crossorigin'
const stream = ctx.body = new PassThrough()
ctx.flushHeaders()
headersFlushed = true
setTimeout(() => {
stream.end(JSON.stringify({ message: 'hello!' }))
})
}, 10)
})
app.listen(async function (err) {
if (err) return done(err)
const server = app.listen()
await once(server, 'listening')
const port = server.address().port
const server = this
const port = this.address().port
try {
const req = http.request({ port })
req.end()
http.request({
port
})
.on('response', res => {
const onData = () => done(new Error('boom'))
res.on('data', onData)
const [res] = await once(req, 'response')
assert(headersFlushed, 'Headers should be flushed')
// shouldn't receive any data for a while
res.removeListener('data', onData)
res.destroy()
done()
server.close()
const dataPromise = new Promise(resolve => {
res.once('data', chunk => {
dataReceived = true
resolve(chunk)
})
.on('error', done)
.end()
})
})
// Wait for data with a timeout
const timeoutPromise = new Promise((resolve, reject) =>
setTimeout(() => reject(new Error('Timeout waiting for data')), 100)
)
await Promise.race([dataPromise, timeoutPromise])
res.destroy()
assert(dataReceived, 'Data should be received after headers')
} finally {
server.close()
}
})
it('should catch stream error', (t, done) => {
it('should catch stream error', async () => {
const PassThrough = require('stream').PassThrough
const app = new Koa()
app.once('error', err => {
@@ -139,9 +151,12 @@ describe('ctx.flushHeaders()', () => {
})
})
request(app.callback()).get('/').end((err) => {
assert(err.message === 'aborted')
done()
})
await request(app.callback()).get('/')
.then(() => {
throw new Error('should not successfully end')
})
.catch(err => {
assert(err.message === 'aborted')
})
})
})

View File

@@ -34,4 +34,10 @@ describe('ctx.get(name)', () => {
assert.ok(ctx.response.get('foo-NULL') === null)
assert.ok(typeof ctx.response.get('FOO-undefined') === 'undefined')
})
it('should return undefined for non-existent headers', () => {
const ctx = context()
assert.strictEqual(ctx.response.get('nonexistent'), undefined)
assert.strictEqual(ctx.response.get(''), undefined)
})
})

View File

@@ -28,21 +28,18 @@ describe('ctx.redirect(url)', () => {
assert.strictEqual(ctx.status, 302)
})
it('should auto fix not encode url', (t, done) => {
it('should auto fix not encode url', async () => {
const app = new Koa()
app.use(ctx => {
ctx.redirect('http://google.com/😓')
})
request(app.callback())
const res = await request(app.callback())
.get('/')
.end((err, res) => {
if (err) return done(err)
assert.strictEqual(res.status, 302)
assert.strictEqual(res.headers.location, 'http://google.com/%F0%9F%98%93')
done()
})
assert.strictEqual(res.status, 302)
assert.strictEqual(res.headers.location, 'http://google.com/%F0%9F%98%93')
})
describe('when html is accepted', () => {

View File

@@ -4,10 +4,11 @@ const { describe, it } = require('node:test')
const assert = require('node:assert/strict')
const Koa = require('../../')
const net = require('net')
const { once } = require('events')
describe('res.writable', () => {
describe('when continuous requests in one persistent connection', () => {
it('should always be writable and respond to all requests', (t, done) => {
it('should always be writable and respond to all requests', async () => {
const app = new Koa()
let count = 0
app.use(ctx => {
@@ -16,83 +17,90 @@ describe('res.writable', () => {
})
const server = app.listen()
const port = server.address().port
const buf = Buffer.from('GET / HTTP/1.1\r\nHost: localhost:' + port + '\r\nConnection: keep-alive\r\n\r\n')
requestTwice(server, (_, datas) => {
const responses = Buffer.concat(datas).toString()
assert.strictEqual(/request 1, writable: true/.test(responses), true)
assert.strictEqual(/request 2, writable: true/.test(responses), true)
done()
server.close()
})
const client = net.connect(port)
const datas = []
function requestTwice (server, done) {
const port = server.address().port
const buf = Buffer.from('GET / HTTP/1.1\r\nHost: localhost:' + port + '\r\nConnection: keep-alive\r\n\r\n')
const client = net.connect(port)
const datas = []
client
.on('error', done)
.on('data', data => datas.push(data))
.on('end', () => done(null, datas))
setImmediate(() => {
client.write(buf)
client.write(buf)
setImmediate(() => client.end())
})
}
client.on('data', data => datas.push(data))
await once(client, 'connect')
client.write(buf)
client.write(buf)
client.end()
await once(client, 'end')
client.destroy()
const responses = Buffer.concat(datas).toString()
assert.strictEqual(/request 1, writable: true/.test(responses), true)
assert.strictEqual(/request 2, writable: true/.test(responses), true)
assert.strictEqual(count, 2) // Add assertion for request count
server.close()
await once(server, 'close')
})
})
describe('when socket closed before response sent', () => {
it('should not be writable', (t, done) => {
it('should not be writable', async () => {
const app = new Koa()
let callback
const promise = new Promise(resolve => { callback = resolve })
app.use(ctx => {
promise.then(() => {
if (ctx.writable) return done(new Error('ctx.writable should not be true'))
done()
server.close()
})
let ctx
let assertionRan = false
app.on('error', () => {})
app.use(c => {
ctx = c
assertionRan = true
})
const server = app.listen()
const port = server.address().port
const buf = Buffer.from('GET / HTTP/1.1\r\nHost: localhost:' + port + '\r\nConnection: keep-alive\r\n\r\n')
const client = net.connect(port)
await once(client, 'connect')
client.write(buf)
requestClosed(server)
await new Promise(resolve => setTimeout(resolve, 5))
client.destroy()
function requestClosed (server) {
const port = server.address().port
const buf = Buffer.from('GET / HTTP/1.1\r\nHost: localhost:' + port + '\r\nConnection: keep-alive\r\n\r\n')
const client = net.connect(port, () => {
client.write(buf)
client.end(() => setTimeout(callback))
})
}
server.close()
await once(server, 'close')
assert(ctx)
assert(assertionRan)
assert(!ctx.writable)
})
})
describe('when response finished', () => {
function request (server) {
const port = server.address().port
const buf = Buffer.from('GET / HTTP/1.1\r\nHost: localhost:' + port + '\r\nConnection: keep-alive\r\n\r\n')
const client = net.connect(port)
setImmediate(() => {
client.write(buf)
})
setTimeout(() => {
client.end()
server.close()
}, 100)
}
it('should not be writable', (t, done) => {
it('should not be writable', async () => {
const app = new Koa()
let assertionRan = false
app.use(ctx => {
ctx.res.end()
if (ctx.writable) return done(new Error('ctx.writable should not be true'))
done()
assert(!ctx.writable)
assertionRan = true
})
request(app.listen())
const server = app.listen()
const port = server.address().port
const buf = Buffer.from('GET / HTTP/1.1\r\nHost: localhost:' + port + '\r\nConnection: keep-alive\r\n\r\n')
const client = net.connect(port)
await once(client, 'connect')
client.write(buf)
await new Promise(resolve => setTimeout(resolve, 5))
client.destroy()
server.close()
await once(server, 'close')
assert(assertionRan)
})
})
})