SuperTest - Testing a Server

12/26/2021, Sun
Categories: #JavaScript #testing
Tags: #NodeJs

Check Content-Type

Testing a simple static file server is made simple when using SuperTest. It permits for the testing of HTTP methods, content-type, response body and many more options.

Supposedly you wish to test a basic http server which serves the common zip, jpg, and html files. This server example uses only the native Nodejs modules: http, fs, and path:

// server.js

// Adapted from https://stackoverflow.com/questions/16333790/node-js-quick-file-server-static-files-over-http/59088331#59088331

import * as http from 'http';
import { IncomingMessage, ServerResponse } from 'http';
import * as fs from 'fs';
import * as path from 'path';

interface CreateServer {
  fileName: string;
}

process.on('uncaughtException',
  err => console.error('uncaughtException', err));
process.on('unhandledRejection',
  err => console.error('unhandledRejection', err));

const mediaTypes: Record<string, string> = {
  zip: 'application/zip',
  jpg: 'image/jpeg',
  html: 'text/html',
}

const createServer = ({ fileName }: CreateServer) => {
  const server = http.createServer(function (_request: IncomingMessage, response: ServerResponse) {
    fs.readFile(fileName, function (err: NodeJS.ErrnoException | null, data: Buffer) {
      if (err) {
        response.statusCode = 404;
        return response.end('File not found or invalid request made.');
      }

      let mediaType = 'text/html';
      const ext = path.extname(fileName);
      if (ext.length > 0 && mediaTypes.hasOwnProperty(ext.slice(1))) {
        mediaType = mediaTypes[ext.slice(1)];
      }

      response.setHeader('Content-Type', mediaType);
      response.end(data);
    })
  });

  return server;
}

export {
  createServer
};

We wish to verify that the index.html file can be served with this test:

// Test

const request = require('supertest');

describe('/', function() {
  it('responds with html', function(done) {
    request(server)
      .get('/')
      .expect('Content-Type', 'text/html')
      .expect(200)
      .end(function (err: any, _res: any) {
        if (err) {
          console.log('Error in the serving of the static html file.');
          return done(err);
        }
        return done();
      });
  });
});

This example uses mocha as the testing framework, where it checks for the presence of a html file on the root url, '/', to be successful with a 200 response when accessed.

SuperTest will also take care of assigning a random port for you when you pass in the server object, so you don't need to worry about assigning a port that is not available.