【问题标题】:Mocha Test connectivity to DBMocha 测试与数据库的连接
【发布时间】:2016-05-02 20:32:00
【问题描述】:

我想使用 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"));
            });
        });
    })
});

我在我的程序上测试了代码,当连接实际失败时,它会抛出一个错误。在这个错误中,我得到了等于 7 的indexOf(ER_ACCESS_DENIED_ERROR)

知道了这一点,为什么我的测试总是通过,我该如何纠正它以满足我的需要?

【问题讨论】:

    标签: mysql node.js express mocha.js


    【解决方案1】:

    您需要告知 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);
            });
        })
    });
    

    【讨论】:

    • "var connection = mysql.createConnection".......对于mysql我需要导入什么包?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多