gpt4 book ai didi

javascript - 变量 isConnected 未更改

转载 作者:行者123 更新时间:2023-11-29 22:22:30 25 4
gpt4 key购买 nike

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;

关于javascript - 变量 isConnected 未更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30577273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com