Mocha测试与数据库的连接 [英] Mocha Test connectivity to DB

查看:228
本文介绍了Mocha测试与数据库的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Mocha测试到数据库的连接性,但是似乎做错了方法,因为无论使用哪种凭据,我总是可以通过我的测试...

I would like to test the connectivity to my DB using Mocha, but it seems that I do it the wrong way since whatever the credentials are, I always got my test passed ...

这是我使用的代码:

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).

I tested the code on my program and when the connection actually fails, it throws an error. Within this error, I get the indexOf(ER_ACCESS_DENIED_ERROR) which is equal to 7.

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

Knowing this, why is my test alway passed and how can I correct it to fit my need?

推荐答案

您需要告知mocha您正在编写的测试是异步的.将完成的回调添加到您的it函数调用中,然后从connection.connect调用此完成的回调.完成的回调足够聪明,可以确定是否将错误作为第一个参数传递,并且万一传递了错误,则测试将失败.

You need to advise mocha that the test you're writing is async. Add a done callback to your it function call and call this done callback from connection.connect. The done callback is clever enough to figure out if an error was passed as first argument and in case an error is passed the test will fail.

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测试与数据库的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆