Chai HTTP
01 / 02

Chai HTTP Basics: Requests, Status & Body Assertions

Chai HTTP: Requests, Status & Body Assertions

Chai HTTP is a plugin for the Chai assertion library, adding HTTP-specific assertions and request-making capability. It's built on superagent (the same underlying HTTP client SuperTest uses), integrated with Chai's familiar expect/should syntax.

Setup & Basic Requests

const chai = require('chai')
const chaiHttp = require('chai-http')
chai.use(chaiHttp)  // registers as a plugin, extending expect
const expect = chai.expect

describe('GET /api/users', () => {
  it('returns 200 with a list of users', async () => {
    // Passing the app instance directly -- no need to manually
    // start/stop a server on a real port
    const res = await chai.request(app).get('/api/users')

    expect(res).to.have.status(200)
    expect(res).to.be.json
    expect(res.body).to.be.an('array')
  })
})

POST with JSON, Query Params & Headers

it('creates a new user', async () => {
  const res = await chai.request(app)
    .post('/api/users')
    .send({ name: 'Alice', email: 'alice@example.com' })  // auto-serialized
    
  expect(res).to.have.status(201)
  expect(res.body).to.have.property('name', 'Alice')
})

it('searches with query parameters', async () => {
  const res = await chai.request(app).get('/search').query({ q: 'test', page: 2 })
  expect(res).to.have.status(200)
})

it('accesses an authenticated endpoint', async () => {
  const res = await chai.request(app)
    .get('/profile')
    .set('Authorization', 'Bearer ' + validToken)

  expect(res).to.have.status(200)
})

Testing Error Responses

it('rejects an invalid payload', async () => {
  const res = await chai.request(app).post('/api/users').send({})
  expect(res).to.have.status(400)
})

it('returns 404 for a missing resource', async () => {
  const res = await chai.request(app).get('/api/users/nonexistent')
  expect(res).to.have.status(404)
})

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free