【问题标题】:TypeError: Cannot read property 'close' of undefinedTypeError:无法读取未定义的属性“关闭”
【发布时间】:2019-04-09 12:26:38
【问题描述】:

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

顺便说一句,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

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

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

【问题讨论】:

  • 也分享require('./database')的代码
  • @front_end_dev 已更新
  • ./database/index.js dbconnect 回调函数不返回任何内容,您在测试脚本index.test.js 中期待close 方法。这就是为什么它给undefined
  • @front_end_dev 那应该怎么做呢?原谅我的无知。
  • 我已经更新了./database/index.js文件,请关注回答。

标签: node.js jestjs koa supertest


【解决方案1】:

更新文件 - ./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)
}

【讨论】:

  • 也许你的意思是return mongoose.Connection?我仍然遇到同样的错误。
  • @tatskie mongoose.connect 返回一个承诺,如果成功建立连接,则承诺解析为undefined。所以我已经返回mongoose.connection 让我们看看它是否有效。
  • 它现在似乎可以工作了。但我在这里遇到了不同的错误imgur.com/Ut3KN33
  • 糟糕,当我运行应用程序(不是测试)时,我无法再连接到数据库。这是错误:Mongoose default connection disconnected Mongoose default connection error: MongoNetworkError: failed to connect to server [undefined:27017] on first connect [MongoNetworkError: getaddrinfo ENOTFOUND undefined undefined:27017]
  • @tatskie 你能在 github 上分享你的代码,这样我就可以在本地下载和运行。光看问题很难理解。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-24
  • 2023-03-28
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多