这是我的mocha测试文件 test-api.js :
var should = require('should');
var mongoose = require('mongoose');
var request = require('supertest');
var db = require('../config/db');
var post = require('../app/models/post');
var faker = require('faker');
describe('Post', function () {
var url = 'http://localhost:3000';
before(function (done) {
var db_url = db.url_test;
mongoose.connect(db_url, done);
});
it('should post a post and get the post back', function (done) {
var _body = {
title: faker.name.title(),
body: faker.lorem.paragraph()
};
//console.log(_body);
request(url)
.post('/api/post')
.send(_body)
.end(function (err, res) {
//if (err) {
// console.log(err);
// //console.log('/api/post post method failed!');
//}
//console.log('res.body: ');
//console.log(res.body);
res.body.should.have.property('url');
res.body.should.have.property('title');
res.body.should.have.property('body');
res.body.should.have.property('date');
done();
});
});
it('should get all the posts', function (done) {
request(url)
.get('/api/post')
.expect(200)
.end(function (err, res) {
if (err) {
console.log(err);
//console.log('/api/post get method failed!')
}
res.body.should.have.property('count');
res.body.should.have.property('limit');
res.body.should.have.property('page');
res.body.should.have.property('results');
//console.log(res.body);
done();
});
});
});
我觉得问题出在before函数里面,因为如果我把mongoose.connect()放在server.js里面 (这是我的api服务器的启动文件), 我就可以正常通过测试.
但是我想在测试文件中临时指定单独的测试用数据库,而不是在server.js里面就指定好,所以把mongoose.connect()放在测试文件内.
这是上面这个mocha测试文件的测试结果:
Post
1) should post a post and get the post back
✓ should get all the posts (52ms)
1 passing (2s)
1 failing
1) Post should post a post and get the post back:
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
我现在也不知道要怎么处理这个问题了,求各位大神帮忙啊!(T_T)...先谢谢大家了!