Node.js Express.js Mocha测试在连接到测试数据库时出现问题
我正试图让我的测试套件在我的express.js应用程序中运行,但这是我的第一个express.js应用程序,也是我第一次与摩卡合作,我不确定如何设置一切 这是我的测验Node.js Express.js Mocha测试在连接到测试数据库时出现问题,node.js,mongodb,express,mocha.js,Node.js,Mongodb,Express,Mocha.js,我正试图让我的测试套件在我的express.js应用程序中运行,但这是我的第一个express.js应用程序,也是我第一次与摩卡合作,我不确定如何设置一切 这是我的测验 should = require 'should' assert = require 'assert' expect = require 'expect' request = require 'superagent' mongoose = require 'mongoose' config = require '../../co
should = require 'should'
assert = require 'assert'
expect = require 'expect'
request = require 'superagent'
mongoose = require 'mongoose'
config = require '../../config/config'
describe "POST", ->
app = require('../../app')
beforeEach (done)->
mongoose.connect config.db, (err) ->
if err
console.log "Error! #{err}"
done()
describe '/users/:id/activities', ->
it 'should return created document', (done) ->
request(app).post('http://localhost:3000/users/1/activities').send(
description: "hello world"
tags: "foo, bar"
).set('Content-Type','application/json')
.end (e, res) ->
console.log(res.body.description)
expect(res.body.description).should.equal('hello world')
done()
我遇到的几个问题是。。。1) 在测试套件中,它无法连接到我的测试数据库(在我的配置文件中);2) 我在尝试post
1) POST /users/:id/activities should return created document:
TypeError: Object #<Request> has no method 'post'
编辑
活动.咖啡(路线)
app.js
require('coffee-script/register');
var express = require('express'),
config = require('./config/config'),
fs = require('fs'),
mongoose = require('mongoose');
mongoose.connect(config.db);
var db = mongoose.connection;
db.on('error', function () {
throw new Error('unable to connect to database at ' + config.db);
});
var modelsPath = __dirname + '/app/models';
fs.readdirSync(modelsPath).forEach(function (file) {
if (/\.coffee$/.test(file)) {
require(modelsPath + '/' + file);
}
});
var app = express();
require('./config/express')(app, config);
app.listen(config.port);
exports.app = app;
首先,一旦superagent指向保存路由、中间件等的应用程序变量,就不需要在superagent提供的方法中指定url。您只需要提供路线,就像这样:
request(app)
.post('/users/123/activities')
.end(function (err, response) {
});
第二,使用摩卡提供的before
语句而不是beforeach
,第二个语句将在您进行的每个单元测试中尝试连接到mongo
对于第一个错误
request has no method 'post'
确保您已安装superagent,并且可以在node\u modules
文件夹中找到它
希望有帮助 谢谢!我将给出一个tryI能够在我的应用程序中定位
superagent
模块的例子。让我粘贴我正在尝试测试的路由。就是这样,您正在从规范代码以及为您的路由提供服务的app.js连接到mongo。你不需要在测试中连接到mongo。啊,明白了!mongo错误(自然)消失了,但现在我得到了1)POST/users/:id/activities应该返回创建的document:Uncaught AssertionError:expected{actual:'hello world'}为'hello world'
,如果在res.body.description的console.log中,我可以看到hello world Returned您正在尝试使用所有可用的断言模块,这是一个错误,您只需要使用一个。更多信息请访问should=require'should'
assert=require'assert'
expect=require'expect'
选择一个您最喜欢的并基于它们的框架进行断言,摩卡网站有一个指向所有这些内容的链接。
request(app)
.post('/users/123/activities')
.end(function (err, response) {
});
request has no method 'post'