Testing

HTTP Test Client

Make real HTTP requests to your AxilJS app in tests with createTestClient, chaining headers, auth tokens and JSON, string or Buffer bodies.

2 min readUpdated DocumentationEdit this page
On this page3

Usage

TypeScript
TS
1import { createTestClient, expect } from '@axiljs/testing'
2
3const client = createTestClient(app)
4
5const list    = await client.get('/users')
6const created = await client.post('/users').send({ name: 'Tariq' })
7const profile = await client.get('/profile').auth(token)          // Authorization: Bearer <token>
8const custom  = await client.get('/data').set('X-Custom', 'value')
9
10expect(list.status).toBe(200)
11expect(list.body.data).toHaveLength(3)

Methods: get, post, put, patch, delete. Each returns a TestRequest; chain set(name, value), auth(token) and send(body), then await it. The response is a TestResponse: status, headers, body (parsed JSON, or the raw string if not JSON) and text.

Request bodies

Objects are JSON-encoded. Requests default to Content-Type: application/json; set('Content-Type', …) replaces it.

Note

Changed in 0.3.3: string and Buffer bodies are sent as-is, byte for byte, whatever the content type. Earlier versions JSON-encoded string bodies a second time when the content type was JSON (the default), so '{"a":1}' arrived as a JSON string instead of an object.

TypeScript
TS
1// Pre-serialized JSON, e.g. to test a webhook signature over req.rawBody
2const payload = JSON.stringify({ event: 'push' })
3await client.post('/webhooks/github')
4  .set('X-Hub-Signature-256', sign(payload))
5  .send(payload)
6
7// Form body
8await client.post('/login')
9  .set('Content-Type', 'application/x-www-form-urlencoded')
10  .send('user=tariq&pass=secret')
11
12// Binary
13await client.post('/upload')
14  .set('Content-Type', 'application/octet-stream')
15  .send(Buffer.from([0x89, 0x50, 0x4e, 0x47]))

Typed helpers

TestRequest is exported (since 0.3.3), so helpers that return a pending request can be typed and emitted in .d.ts files:

TypeScript
TS
1import { createTestClient, type TestRequest } from '@axiljs/testing'
2
3const client = createTestClient(app)
4
5export function asAdmin(path: string): TestRequest {
6  return client.get(path).auth(adminToken)
7}

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY