2016-04-27 123 views
1

嘗試使用Mocha爲使用Msocha的NodeJS設置測試。但每次運行我的測試時,我都會收到「連接已關閉」。摩卡測試nodejs mssql - 連接已關閉

enter image description here

奇怪的是,它工作時,我本身運行的應用程序,然後,我得到的數據從數據庫中背部和連接不太早關閉。

我的測試代碼:

var express = require('express'); 
var expect = require('chai').expect; 
var calendar = require('./../Server/calendarDatabase'); 

describe("Calendar", function() { 
    describe("Database", function() { 
     it("should get stuff from the database", function (done) { 
      calendar.getAll().then(function (returnValue) { 
       console.dir(returnValue); 
       expect(returnValue.count).to.equal(5); 
       done(); 
      }); 
     }); 
    }); 
}); 

我calendarDatabase的代碼是什麼樣子

var express = require('express'); 
var sql = require('mssql'); 

var config = require('./../config'); 

var calendarDbConnection = {}; 

sql.connect(config.mssql, function (err) { 
    console.log(err); 
}); 

calendarDbConnection.getAll = function() { 
    return new sql.Request() 
     .query('select * from Human') 
     .then(function (recordsets) { 
     return recordsets; 
    }) 
     .catch(function (err) { 
     console.log(err.message); 
    }); 
} 

module.exports = calendarDbConnection; 

最後,這是我使用運行應用程序時:

var express = require('express'); 
var router = express.Router(); 

var calendarDb = require('./../Server/calendarDatabase'); 

router.get("/", function (request, response) { 
    response.render('calendar', { title: 'Calendar app title' }); 
}); 

router.get('/getYear/:year', function (request, response) { 
    calendarDb.getAll().then(function(returnValue) { 
     console.dir(returnValue); 
    }); 
    response.send(); 
}); 

module.exports = router; 

所以我的問題是,爲什麼在使用Mocha進行測試時無法正常工作,但是它在運行應用程序本身時還是如此?我在這裏錯過了什麼?

回答

1

我的連接似乎因爲框架沒有保持打開而關閉。 使我的聯繫承諾有效。

describe("Calendar", function() { 
    describe("Database", function() { 
     it("should get stuff from the database", function (done) { 
      calendar.Connect().then(function() { 
       calendar.getAll().then(function (returnValue) { 
        console.dir(returnValue); 
        expect(returnValue.count).to.equal(5); 
       }).done(); 
      }); 
     }); 
    }); 
}); 

日曆DB:

calendarDbConnection.Connect = function() { 
    return sql.connect(config.mssql);  
}