我在使用Express和Sequelize设置测试时遇到了问题 . 我正在使用摩卡柴进行测试 . 我现在只是想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,但在chai.request.get.then得到404(/ 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应显示欢迎消息:错误:超出2000ms超时 . 对于异步测试和钩子,确保调用“done()”;如果返回Promise,请确保它已解决 .
没必要告诉你我从那些测试的东西开始(最后......)因此,我还没有得到所有的东西 . 非常感谢你的帮助 !
PAM
1 回答
UnhandledPromiseRejectionWarning
你来自你的测试,尝试在断言块之后执行.then(done, done)
而不是调用done()
并添加.catch
块 .此外,关于404,这是因为您在
sequelize.authenticate()
承诺内设置路线,因此当您导出应用程序进行测试时,路由不会设置 . 只需在Promise上方移动路线定义(并添加app.use('/', router);
语句,否则不会使用您的路线) .