我在使用Express和Sequelize设置测试时遇到了问题。我使用Mocha + Chai进行测试。我现在只想尝试ping。
server.js代码:
const express = require('express');
const Sequelize = require('sequelize');
const bodyParser = require('body-parser');
const db = require('./config/db');
const app = express();
const router = express.Router();
const PORT = 8000;
//Use body parser for express
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const sequelize = new Sequelize(db.database, db.user, db.password, {
host: db.host,
dialect: 'mysql',
operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
sequelize
.authenticate()
.then(() => {
//Import Routes
require('./app/routes/')(router, sequelize);
router.get('/', (req, res) => {
res.json('Welcome to Dickson Connect API :)');
})
//Make express Listen
app.listen(PORT, () => {
console.log('We are live on ' + PORT);
})
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
//For chai testing
module.exports = app;
服务器正在运行。
和test.js:
const chai = require('chai');
const chaitHttp = require('chai-http');
const server = require('../../server');
const should = chai.should();
chai.use(chaitHttp);
describe('/GET', () => {
it('should display a welcome message', (done) => {
chai.request(server)
.get('/')
.then( (res) => {
res.should.have.status(200);
done();
})
.catch( err => {
throw err;
})
})
})
我相信至少部分问题是我的服务器正在返回一个包含快速应用程序的续集实例,这可能不是通常的情况。虽然,续集只是我在chai测试中等待的承诺,使用then
代替end
。
这是我得到的错误:
/ GET (node:35436)UnhandledPromiseRejectionWarning:AssertionError:expected {Object(domain,_events,...)}的状态代码为200但得到了404 在chai.request.get.then(/Applications/MAMP/htdocs/api_dickson/app/routes/index.test.js:16:23) 在 at process._tickCallback(internal / process / next_tick.js:188:7) (node:35436)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这个错误源于在没有catch块的情况下抛出异步函数,或者拒绝未使用.catch()处理的promise。 (拒绝ID:1) (节点:35436)[DEP0018]弃用警告:不推荐使用未处理的拒绝承诺。将来,未处理的承诺拒绝将使用非零退出代码终止Node.js进程。 执行(默认):SELECT 1 + 1 AS结果 我们活在8000 1)应显示欢迎信息
0传球(2s) 1失败
1)/ GET 应显示欢迎信息: 错误:超出2000毫秒的超时。对于异步测试和挂钩,请确保" done()"叫做;如果返回Promise,请确保它已解决。
无需告诉你我从那些测试开始(最后......)因此,我还没有得到所有的东西。非常感谢你的帮助!
PAM
答案 0 :(得分:1)
您的UnhandledPromiseRejectionWarning
来自您的测试,请在断言块之后尝试.then(done, done)
,而不是调用done()
并添加.catch
块。
it('should display a welcome message', (done) => {
chai.request(server).get('/')
.then((res) => {
res.should.have.status(200);
})
.then(done, done);
})
此外,关于404,这是因为您在sequelize.authenticate()
承诺内设置路线,因此当您导出应用程序进行测试时,路由未设置。只需移动路线定义(并在Promise上方添加app.use('/', router);
语句,否则不会使用您的路线)。
(...)
const sequelize = new Sequelize(...);
require('./app/routes/')(router, sequelize);
router.get('/', (req, res) => {
res.json('Welcome to Dickson Connect API :)');
})
app.use("/", router);
sequelize
.authenticate()
.then(() => {
//Make express Listen
app.listen(PORT, () => {
console.log('We are live on ' + PORT);
})
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
//For chai testing
module.exports = app;