Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix "not ok timeout!" when testing fastify route?

I am trying to test fastify route with tap. Here is the test file:

const tap = require('tap')
const buildFastify = require('../../src/app')

tap.test('GET `/` route', t => {
    t.plan(4)

    const fastify = buildFastify()

    // At the end of your tests it is highly recommended to call `.close()`
    // to ensure that all connections to external services get closed.
    t.tearDown(() => {
        fastify.close();
    });

    fastify.inject({
        method: 'GET',
        url: '/'
    }, async (err, response) => {
        t.error(err)
        t.strictEqual(response.statusCode, 200)
        t.strictEqual(response.headers['content-type'], 'application/json; charset=utf-8')
        t.deepEqual(JSON.parse(response.payload), { hello: 'world' })
        t.done()
    })
})

After running test I see in the console:

....Closing mongoose connection ...
listening on 3001
tests/routes/status.test.js ........................... 4/5 30s
  not ok timeout!

running tests with npm script: "test": "env-cmd ./test.env tap tests/routes/status.test.js"

Here is the app.js with buildFastify function: buildFastify on gist

like image 936
gandra404 Avatar asked Oct 20 '25 05:10

gandra404


1 Answers

Hm...i have got the same problem today. I tried to write a plugin for mongoose connection and met tap timeout.

The solution was to close DB connection on 'onClose' hook, Fastify doesn't do this by default.

I see that you have 'onClose' hook inside your code and very surprised that this is not working.

'use strict'

const fp = require('fastify-plugin');
const Mongoose = require('mongoose');
const Bluebird = require('bluebird');

Mongoose.Promise = Bluebird;

module.exports = fp(async function (fastify, { mongoURI }) {
  try {
    const db = await Mongoose.connect( mongoURI, {
      useNewUrlParser: true,
    } );

    fastify
      .decorate( 'mongoose', db )
      .addHook( 'onClose', ( fastify, done ) => {
        fastify.mongoose.connection.close();
      } );
  }
  catch( error ) {
    console.log(`DB connection error: `, error);
  }
})
like image 75
Toomean Avatar answered Oct 21 '25 20:10

Toomean