Testing HTTP Accept-Encoding Header Processing in Koa.js
This test suite validates the acceptsEncodings functionality in Koa’s request handling, focusing on how the framework processes HTTP Accept-Encoding headers and determines the optimal content encoding. The tests cover various scenarios including empty headers, multiple encoding options, and quality preferences.
Test Coverage Overview
Implementation Analysis
Technical Details
Best Practices Demonstrated
koajs/koa
__tests__/request/acceptsEncodings.test.js
'use strict'
const { describe, it } = require('node:test')
const assert = require('assert')
const context = require('../../test-helpers/context')
describe('ctx.acceptsEncodings()', () => {
describe('with no arguments', () => {
describe('when Accept-Encoding is populated', () => {
it('should return accepted types', () => {
const ctx = context()
ctx.req.headers['accept-encoding'] = 'gzip, compress;q=0.2'
assert.deepStrictEqual(ctx.acceptsEncodings(), ['gzip', 'compress', 'identity'])
assert.strictEqual(ctx.acceptsEncodings('gzip', 'compress'), 'gzip')
})
})
describe('when Accept-Encoding is not populated', () => {
it('should return identity', () => {
const ctx = context()
assert.deepStrictEqual(ctx.acceptsEncodings(), ['identity'])
assert.strictEqual(ctx.acceptsEncodings('gzip', 'deflate', 'identity'), 'identity')
})
})
})
describe('with multiple arguments', () => {
it('should return the best fit', () => {
const ctx = context()
ctx.req.headers['accept-encoding'] = 'gzip, compress;q=0.2'
assert.strictEqual(ctx.acceptsEncodings('compress', 'gzip'), 'gzip')
assert.strictEqual(ctx.acceptsEncodings('gzip', 'compress'), 'gzip')
})
})
describe('with an array', () => {
it('should return the best fit', () => {
const ctx = context()
ctx.req.headers['accept-encoding'] = 'gzip, compress;q=0.2'
assert.strictEqual(ctx.acceptsEncodings(['compress', 'gzip']), 'gzip')
})
})
})