isConnected应该是一个变量,用于测试数据库连接是否成功。现在在我的DatabaseTest类中,我要声明此isConnected变量。 isConnected在数据库对象中声明,因此应该可以通过database.isConnected访问。但是在makeConnection()和closeConnection()中该值不会更改。我怀疑这是因为isConnected不是全局变量。另外,当我在var mysql行之后将其声明为var isConnected时,它也不更新。
我是否缺少一些基本的示波器基础知识?

var mysql = require('mysql');

//Database
var database = {

isConnected: false,

makeConnection: function(){

    var connectionString = {
        host: '192.168.1.3',
        port: 3306,
        user: 'root',
        password: 'secret',
        database: 'user_profile_database'
    };

    var activeConnection = mysql.createConnection(connectionString);
    activeConnection.connect(function(error){
            if(error){
                throw error;
            }
            console.log("Successfull connection!");
        });
        isConnected = true;
    return activeConnection;
},

closeConnection: function(activeConnection){
    activeConnection.end(function(error){
        if(error){
            throw error;
        }
        console.log("Successfull disconnetion!");
    });
    isConnected = false;
  }
}

module.exports = database;


所以这是测试用例:

var database = require('../Code/Database/Database');
var expect = require('chai').expect;

//Tests for the Database class.
describe("#Database", function(){

//Test for the makeConnection method
describe("#makeConnection", function(){

    it("should make a connection with the database", function(){
        expect(database.isConnected).to.be.false;
        var connection = database.makeConnection();
        expect(database.isConnected).to.be.true;
    })
  })
})

最佳答案

makeConnetion()closeConnection()方法中,应将isConnected称为this.isConnected

例如:

var mysql = require('mysql');

//Database
var database = {

isConnected: false,

makeConnection: function(){

    var connectionString = {
        host: '192.168.1.3',
        port: 3306,
        user: 'root',
        password: 'secret',
        database: 'user_profile_database'
    };

    var activeConnection = mysql.createConnection(connectionString);
    activeConnection.connect(function(error){
            if(error){
                throw error;
            }
            console.log("Successfull connection!");
        });
        this.isConnected = true; // instead of just isConnected
    return activeConnection;
},

closeConnection: function(activeConnection){
    activeConnection.end(function(error){
        if(error){
            throw error;
        }
        console.log("Successfull disconnetion!");
    });
    this.isConnected = false; // instead of just isConnected
  }
}

module.exports = database;

10-04 21:30