最佳答案
我已经编写了一个非常简单的 CRUD API,并且最近开始使用 chai
和 chai-http
编写一些测试代码,但是在使用 $ mocha
运行测试时遇到了一个问题。
当我运行测试时,我在 shell 上得到以下错误:
Address 不是函数
下面是我的一个测试(/test/server-test. js)的例子:
var chai = require('chai');
var mongoose = require('mongoose');
var chaiHttp = require('chai-http');
var server = require('../server/app'); // my express app
var should = chai.should();
var testUtils = require('./test-utils');
chai.use(chaiHttp);
describe('API Tests', function() {
before(function() {
mongoose.createConnection('mongodb://localhost/bot-test', myOptionsObj);
});
beforeEach(function(done) {
// I do stuff like populating db
});
afterEach(function(done) {
// I do stuff like deleting populated db
});
after(function() {
mongoose.connection.close();
});
describe('Boxes', function() {
it.only('should list ALL boxes on /boxes GET', function(done) {
chai.request(server)
.get('/api/boxes')
.end(function(err, res){
res.should.have.status(200);
done();
});
});
// the rest of the tests would continue here...
});
});
还有我的 express
应用程序文件(/server/app.js) :
var mongoose = require('mongoose');
var express = require('express');
var api = require('./routes/api.js');
var app = express();
mongoose.connect('mongodb://localhost/db-dev', myOptionsObj);
// application configuration
require('./config/express')(app);
// routing set up
app.use('/api', api);
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('App listening at http://%s:%s', host, port);
});
及(服务器/路由/api.js) :
var express = require('express');
var boxController = require('../modules/box/controller');
var thingController = require('../modules/thing/controller');
var router = express.Router();
// API routing
router.get('/boxes', boxController.getAll);
// etc.
module.exports = router;
在运行测试之前,我已经尝试在 /test/server-test. js文件中注销 server
变量:
...
var server = require('../server/app'); // my express app
...
console.log('server: ', server);
...
结果是一个空对象: server: {}
。