2014-09-10 2 views
0

Я пытаюсь запустить свой тестовый набор в моем приложении express.js, но это мое первое приложение express.js, а также мое первое время, работающее с моккой и Я не уверен, как все наладить.Экспресс-тесты Mocha, имеющие проблемы с подключением к тесту db

Вот мой тест

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' 

Может кто-то мне точку в правильном направлении, о том, как получить все работает должным образом?

Ошибка я получаю назад от попыток подключения к MongoDB является Error! Error: Trying to open unclosed connection.

Я бегу мокко пакет, выполнив эту команду

NODE_ENV=test mocha test/controllers/activities.test.coffee --compilers coffee:coffee-script/register -R spec 

Редактировать

activities.coffee (маршруты)

express = require 'express' 
router = express.Router() 
mongoose = require 'mongoose' 
Activity = mongoose.model 'Activity' 

module.exports = (app) -> 
    app.use '/', router 

router.post '/users/:id/activities', (req, res, next) -> 
    activity = Activity(
    user_id: req.params.id 
    description: req.body.description, 
    tags: req.body.tags 
) 

    activity.save (err)-> 
    if not err 
     res.json(activity) 
    else 
     res.json({ error: err }) 

router.get '/users/:id/activities/:activity_id', (req, res, next) -> 
    Activity.findById req.params.activity_id, (err, activity) -> 
    if not err 
     res.json(activity) 
    else 
     res.json({ error: err }) 

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; 

ответ

1

Во-первых, как только у вас есть SuperAgent указывая вам приложение переменную, которая держит вас маршруты, промежуточное программное и так далее, нет никакой необходимости, чтобы указать URL в методах, предусмотренных SuperAgent. Вам просто нужно обеспечить маршрут, как так:

request(app) 
    .post('/users/123/activities') 
    .end(function (err, response) { 
    }); 

Во-вторых, использовать before заявление, предоставленную мокко вместо beforeEach, второй будет пытаться подключиться к Монго на каждом модульном тесте у вас есть.

Для первой ошибки

request has no method 'post' 

Убедитесь, что вы установили SuperAgent и вы можете найти его на папку node_modules.

Надеюсь, что это поможет!

+0

Спасибо! Я собираюсь дать это попробовать – dennismonsewicz

+0

Мне удалось найти модуль «superagent» в моем приложении. Позвольте мне вставить Маршрут, который я пытаюсь проверить. – dennismonsewicz

+0

. Вот он, вы подключаетесь к mongo из вашего спецификационного кода, а также из вашего app.js, которые служат вашим маршрутам. Вам не нужно подключаться к монго в своем тесте. –