测试快速路由时如何解决"not ok timeout!"?



>我正在尝试用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"

这是具有buildFastify函数的app.js:buildFastify on gist

嗯...我今天遇到了同样的问题。我试图为猫鼬连接编写一个插件,并遇到了点击超时。

解决方案是在"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);
  }
})

最新更新