Mocha 测试与数据库的连接
Mocha Test connectivity to DB
我想使用 Mocha 测试与我的数据库的连接,但似乎我做错了,因为无论凭据是什么,我总能通过测试...
这是我使用的代码:
describe('Access to DB', function(){
describe('#fail', function(){
it('should return -1 because wrong credentials', function(){
var connection = mysql.createConnection({
host: 'right host',
user: 'wrong user',
password: 'wrong password',
database: 'right database'
});
connection.connect(function(err){
assert.equal(7,err.stack.indexOf("ER_ACCESS_DENIED_ERROR"));
});
});
})
});
我在我的程序上测试了代码,当连接实际失败时,它会抛出一个错误。在此错误中,我得到 indexOf(ER_ACCESS_DENIED_ERROR)
等于 7。
知道了这一点,为什么我的测试总是通过,我该如何更正它以满足我的需要?
您需要告知 mocha 您正在编写的测试是异步的。向您的 it
函数调用添加一个完成回调,并从 connection.connect 调用这个完成回调。 done 回调非常聪明,可以判断错误是否作为第一个参数传递,如果传递了错误,测试将失败。
describe('Access to DB', function(){
describe('#fail', function(){
it('should return -1 because wrong credentials', function(done){
var connection = mysql.createConnection({
host: 'right host',
user: 'wrong user',
password: 'wrong password',
database: 'right database'
});
connection.connect(done);
});
})
});
我想使用 Mocha 测试与我的数据库的连接,但似乎我做错了,因为无论凭据是什么,我总能通过测试...
这是我使用的代码:
describe('Access to DB', function(){
describe('#fail', function(){
it('should return -1 because wrong credentials', function(){
var connection = mysql.createConnection({
host: 'right host',
user: 'wrong user',
password: 'wrong password',
database: 'right database'
});
connection.connect(function(err){
assert.equal(7,err.stack.indexOf("ER_ACCESS_DENIED_ERROR"));
});
});
})
});
我在我的程序上测试了代码,当连接实际失败时,它会抛出一个错误。在此错误中,我得到 indexOf(ER_ACCESS_DENIED_ERROR)
等于 7。
知道了这一点,为什么我的测试总是通过,我该如何更正它以满足我的需要?
您需要告知 mocha 您正在编写的测试是异步的。向您的 it
函数调用添加一个完成回调,并从 connection.connect 调用这个完成回调。 done 回调非常聪明,可以判断错误是否作为第一个参数传递,如果传递了错误,测试将失败。
describe('Access to DB', function(){
describe('#fail', function(){
it('should return -1 because wrong credentials', function(done){
var connection = mysql.createConnection({
host: 'right host',
user: 'wrong user',
password: 'wrong password',
database: 'right database'
});
connection.connect(done);
});
})
});