我是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
答案 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)
}