[Fixed] How to write api request tests without launching server?


It is possible to launch server on port and test it with library "supertest".
I’m wondering if it’s possible to do the same without running a server?

Express app, the same as fastify app or others, takes request and response arguments from native node under the hood, like this:

const server = http.createServer((req, res) => {

So it should be possible to call that callback directly from tests.
How to get that callback? Is there any toolkit to help with constructing request and response objects for the callback?

The reason – just to make tests faster. As I don’t want to test HTTP protocol and internals of node, I’d like to save time by skipping it.


Fastify has this feature out of the box:

'use strict'

const { test } = require('tap')
const Fastify = require('fastify')

test('requests the "/" route', async t => {
  const fastify = Fastify()

  fastify.get('/', function (request, reply) {
    reply.send({ hello: 'world' })

  const response = await app.inject({
    method: 'GET',
    url: '/'
  t.strictEqual(response.statusCode, 200, 'returns a status code of 200')

To moch the req/resp object it is used light-my-request under the hood

Leave a Reply

(*) Required, Your email will not be published