变量isConnected未更改

时间:2015-06-01 15:23:09

标签: javascript mysql scope mocha chai

isConnected应该是一个变量来测试数据库连接是否成功。现在在我的DatabaseTest类中,我想声明这个isConnected变量。 isConnected在数据库对象中声明,因此它应该可以通过database.isConnected访问。但是在makeConnection()和closeConnection()中没有更改该值。我怀疑这是因为isConnected不是全局变量。此外,当我在var mysql行之后将其声明为var isConnected时,它也不会更新它。 我错过了一些基本的范围基础吗?

activate_this.py

所以这是测试用例:

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;

1 个答案:

答案 0 :(得分:0)

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;