2

我正在尝试使用tap. 这是测试文件:

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()
    })
})

运行测试后,我在控制台中看到:

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

使用 npm 脚本运行测试: "test": "env-cmd ./test.env tap tests/routes/status.test.js"

这是app.jswith buildFastify函数:buildFastify on gist

4

1 回答 1

2

嗯……我今天也遇到了同样的问题。我试图为猫鼬连接编写一个插件并遇到水龙头超时。

解决方案是在 'onClose' 钩子上关闭数据库连接,Fastify 默认不这样做。

我看到你的代码中有“onClose”钩子,很惊讶这不起作用。

'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);
  }
})

于 2019-08-07T22:00:49.890 回答