SnapAPI/src/middleware/__tests__/compression.test.ts
Hoid 5137b80a2a
All checks were successful
Build & Deploy to Staging / Build & Deploy to Staging (push) Successful in 11m50s
test: add middleware tests for auth, compression, and usage
- auth.test.ts (8 tests): missing key, Bearer/X-API-Key/query extraction, priority, invalid key, apiKeyInfo attachment
- compression.test.ts (5 tests): gzip for text/json, skip for images/small/no-accept
- usage.test.ts (7 tests): no keyInfo passthrough, tracking with headers, increment, 429 on limit, month reset, DB load, error handling

Total: 20 new tests, 205 passing (was 190)
2026-03-03 12:16:28 +01:00

65 lines
1.9 KiB
TypeScript

import { describe, it, expect } from 'vitest'
import express from 'express'
import request from 'supertest'
import { compressionMiddleware } from '../compression.js'
function createApp() {
const app = express()
app.use(compressionMiddleware)
app.get('/text', (_req, res) => {
// Send enough data to exceed 1024 byte threshold
res.type('text/html').send('x'.repeat(2000))
})
app.get('/small', (_req, res) => {
res.type('text/html').send('small')
})
app.get('/image', (_req, res) => {
res.type('image/png').send(Buffer.alloc(2000))
})
app.get('/json', (_req, res) => {
res.type('application/json').send(JSON.stringify({ data: 'y'.repeat(2000) }))
})
return app
}
describe('compressionMiddleware', () => {
it('compresses text responses above threshold', async () => {
const res = await request(createApp())
.get('/text')
.set('Accept-Encoding', 'gzip')
expect(res.headers['content-encoding']).toBe('gzip')
})
it('does not compress responses below threshold', async () => {
const res = await request(createApp())
.get('/small')
.set('Accept-Encoding', 'gzip')
expect(res.headers['content-encoding']).toBeUndefined()
})
it('does not compress image responses', async () => {
const res = await request(createApp())
.get('/image')
.set('Accept-Encoding', 'gzip')
expect(res.headers['content-encoding']).toBeUndefined()
})
it('compresses JSON responses above threshold', async () => {
const res = await request(createApp())
.get('/json')
.set('Accept-Encoding', 'gzip')
expect(res.headers['content-encoding']).toBe('gzip')
})
it('does not compress when client does not accept gzip', async () => {
const res = await request(createApp())
.get('/text')
.set('Accept-Encoding', 'identity')
expect(res.headers['content-encoding']).toBeUndefined()
})
})