我在用Express和Sequelize设置测试时有问题。我用摩卡+柴做测试。我只是暂时试着点球。
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;
})
})
})我认为至少有一部分问题是,我的服务器正在返回一个包含express应用程序的续集实例,这可能不是通常的情况。不过,续写只是我在chai测试中等待的一个承诺,使用then而不是end。
这是我正在犯的错误:
(/Applications/MAMP/htdocs/api_dickson/app/routes/index.test.js:16:23) ( /GET :35436) UnhandledPromiseRejectionWarning: AssertionError:预期的{ Object (域,_events,.)}具有状态代码200,但在chai.request.get.then的process._tickCallback (process._tickCallback/process/next_tick.js:188:7)(节点:35436) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误起源于在异步函数中抛出而不带catch块,或者拒绝使用.catch()处理的承诺。(拒绝id: 1) (节点:35436) DEP0018 DeprecationWarning:未处理的承诺拒绝被取消。在未来,承诺不处理的拒绝将使用非零退出代码终止Node.js进程。执行(默认):选择1+1作为结果我们活在8000上)应该显示一条欢迎消息 0传球(2s) 1不及格 1) /GET应该显示一条欢迎消息:错误:超过2000 of的超时。对于异步测试和钩子,请确保调用"done()“;如果返回承诺,则确保它已解决。
没必要告诉你我要从那些测试开始(终于.)因此,我还没有得到所有的东西。非常感谢你的帮助!
帕姆
发布于 2018-04-06 07:57:51
您的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()承诺中设置了您的路由,所以当您为测试导出应用程序时,不会设置这些路由。只需移动路由定义(并添加一个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;https://stackoverflow.com/questions/49675711
复制相似问题