变量 isConnected 没有改变

Variable isConnected is not changed

isConnected 应该是一个变量来测试数据库连接是否成功。现在在我的 DatabaseTest class 中,我想断言这个 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;