Mastering Chai-HTTP with Dozens of Practical API Examples

Introduction to Chai-HTTP

Chai-HTTP is an extension of the Chai assertion library used for testing HTTP services in Node.js applications. This powerful tool allows developers to perform HTTP assertions, making it an essential component for testing API endpoints.

Installing Chai-HTTP

  
    npm install chai-http --save-dev
  

Basic Usage

Chai-HTTP provides a simple and intuitive interface for performing HTTP assertions. Below is a basic example of how to use it:

  
    const chai = require('chai');
    const chaiHttp = require('chai-http');
    const server = require('../server');
    const should = chai.should();

    chai.use(chaiHttp);

    describe('GET /', () => {
      it('it should GET the home page', (done) => {
        chai.request(server)
            .get('/')
            .end((err, res) => {
              res.should.have.status(200);
              res.body.should.be.a('object');
              done();
            });
      });
    });
  

Advanced Usage and More APIs

Let’s explore some advanced usage scenarios and various API endpoints:

GET Request

  
    chai.request(server)
        .get('/api/users')
        .end((err, res) => {
          res.should.have.status(200);
          res.body.should.be.a('array');
        });
  

POST Request

  
    chai.request(server)
        .post('/api/users')
        .send({ name: 'John Doe', age: 30 })
        .end((err, res) => {
          res.should.have.status(201);
          res.body.should.be.a('object');
          res.body.should.have.property('name').eql('John Doe');
        });
  

PUT Request

  
    chai.request(server)
        .put('/api/users/1')
        .send({ name: 'Jane Doe' })
        .end((err, res) => {
          res.should.have.status(200);
          res.body.should.be.a('object');
          res.body.should.have.property('name').eql('Jane Doe');
        });
  

DELETE Request

  
    chai.request(server)
        .delete('/api/users/1')
        .end((err, res) => {
          res.should.have.status(204);
        });
  

Authentication and Headers

  
    chai.request(server)
        .get('/api/protected')
        .set('Authorization', 'Bearer YOUR_TOKEN_HERE')
        .end((err, res) => {
          res.should.have.status(200);
        });
  

Testing JSON Response Content

  
    chai.request(server)
        .get('/api/user/1')
        .end((err, res) => {
          res.should.have.status(200);
          res.body.should.be.a('object');
          res.body.should.have.property('id').eql(1);
        });
  

Testing HTML Response

  
    chai.request(server)
        .get('/about')
        .end((err, res) => {
          res.should.have.status(200);
          res.text.should.include('About Us');
        });
  

Practical App Example

Let’s consider a simple Express app example integrating the above APIs:

  
    const express = require('express');
    const bodyParser = require('body-parser');
    const app = express();

    app.use(bodyParser.json());

    const users = [];

    app.get('/api/users', (req, res) => {
      res.status(200).json(users);
    });

    app.post('/api/users', (req, res) => {
      const user = { id: users.length + 1, ...req.body };
      users.push(user);
      res.status(201).json(user);
    });

    app.put('/api/users/:id', (req, res) => {
      const user = users.find(u => u.id == req.params.id);
      user.name = req.body.name;
      res.status(200).json(user);
    });

    app.delete('/api/users/:id', (req, res) => {
      const index = users.findIndex(u => u.id == req.params.id);
      users.splice(index, 1);
      res.status(204).send();
    });

    module.exports = app;

    if (require.main === module) {
      app.listen(3000, () => {
        console.log('Server is running on port 3000');
      });
    }
  

By integrating Chai-HTTP, you can ensure that your API endpoints are properly tested, making your application more robust and reliable.

Hash: 27b39d7bbaf969e0cf9f6bc49e64a8b2d49533d7faefe94d882aa070fbb3a0a8

Leave a Reply

Your email address will not be published. Required fields are marked *