Chai HTTP

5.1.2 · active · verified Tue Apr 21

Chai HTTP is an assertion plugin for the Chai Assertion Library, designed specifically for conducting HTTP integration tests. It enables developers to test HTTP APIs by composing requests and asserting on their responses, supporting both web applications (like Express or Connect apps) and external URLs. The library uses Superagent under the hood for making HTTP requests. The current stable version is 5.1.2, which maintains an active release cadence with multiple updates in the past year, indicating sustainable maintenance and a popular standing within the Node.js ecosystem. Key differentiators include its fluent, chainable API for request creation, automatic server management for local applications (starting and stopping it), and comprehensive assertions for common HTTP tasks like status codes, headers, and body content. It ships with TypeScript types, enhancing developer experience in TypeScript projects.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up Chai HTTP with an Express app, sending a GET request, and asserting the response status and text, and a POST request with data.

import * as chai from 'chai';
import chaiHttp from 'chai-http';
import { request } from 'chai-http';
import express from 'express';

chai.use(chaiHttp);
const expect = chai.expect;

const app = express();
app.get('/', (req, res) => {
  res.status(200).send('Hello Chai HTTP!');
});

app.post('/data', (req, res) => {
  res.status(201).json({ received: req.body });
});

describe('Chai HTTP Basic Test', () => {
  it('should get a 200 response from the root path', (done) => {
    request.execute(app)
      .get('/')
      .end((err, res) => {
        expect(err).to.be.null;
        expect(res).to.have.status(200);
        expect(res.text).to.equal('Hello Chai HTTP!');
        done();
      });
  });

  it('should post data and get a 201 response', (done) => {
    request.execute(app)
      .post('/data')
      .send({ key: 'value' })
      .end((err, res) => {
        expect(err).to.be.null;
        expect(res).to.have.status(201);
        expect(res.body).to.deep.equal({ received: {} }); // Express needs body-parser for req.body
        done();
      });
  });
});

view raw JSON →