TypeError:无法读取未定义的属性“ close”

时间:2018-11-06 05:45:10

标签: node.js jestjs koa supertest

我是nodejs和koa的新手。有一个现有的Koa应用程序(运行正常且没有问题),我正在尝试使用Jest编写测试代码。我搜索了可能适用于这种情况的样本测试,但无济于事。现在,当我运行测试代码containerTemplate时出现此错误。我知道从TypeError: Cannot read property 'close' of undefined初始化server变量有问题。

顺便说一句,ret返回console.log(ret)

undefined

这是我想用[nodemon] restarting due to changes... [nodemon] starting `node index.js` undefined Mongoose default connection open to mongodb://localhost/giantsoftdata Listening to port: 3000 测试的现有应用程序:

npm run test

这是我的测试代码:

// index.js
const Koa = require('koa')
const KoaBodyParser = require('koa-bodyparser')
const KoaErrorHandler = require('@giansoft/lib-errors/lib/koaHandler')
const PORT = 3000
const app = new Koa()
const router = require('./api/rest/router')()
const dbconnect = require('./database')
const dbstatus = require('./database/dbstatus')

app
  .use(KoaErrorHandler)
  .use(dbstatus())
  .use(KoaBodyParser())

const ret = dbconnect( async function () {
  app
      .use(router.routes())
      .use(router.allowedMethods())
  app.listen(PORT, () => {
      console.log(`Listening to port: ${PORT}`)
  })
  return app;
})
// console.log(ret)
module.exports = ret;

这里是// index.test.js const server = require("../index"); const request = require("supertest"); afterEach(() => { server.close(); }); describe('routes: /status', () => { test('Should respond {Status : "Ok"}.', async () => { const response = await request(server).get('/status'); expect(response.status).toEqual(200); expect(response.type).toEqual('application/json'); }); });

./database/index.js

1 个答案:

答案 0 :(得分:0)

更新的文件-./database/index.js

const mongoose = require('mongoose')
const dbConfig = require('../config').db

const dbconnect = (callback) => {
  let connString = `mongodb://${dbConfig.host}`
  if (dbConfig.username && dbConfig.password) {
    connString = `mongodb://${dbConfig.username}:${dbConfig.password}@${dbConfig.host}`
  }

  mongoose.connect(connString, { useNewUrlParser: true, useCreateIndex: true })

  mongoose.connection.on('open', function () {
    callback()
  })

  mongoose.connection.on('connected', function () {
    console.log('Mongoose default connection open to ' + connString)
  })

  mongoose.connection.on('error', function (err) {
    console.log('Mongoose default connection error: ' + err)
  })

  mongoose.connection.on('disconnected', function () {
    console.log('Mongoose default connection disconnected')
  })

  process.on('SIGINT', function () {
    mongoose.connection.close(function () {
      console.log('Mongoose default connection closed through app termination')
      process.exit(0)
    })
  });
  return mongoose.connection;
}

module.exports = (callback) => {
  return dbconnect(callback)
}