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
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);
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With