mysql Mocha测试与数据库的连接

vfwfrxfs  于 2023-11-16  发布在  Mysql
关注(0)|答案(2)|浏览(96)

我想使用Mocha测试到我的DB的连接,但似乎我用错了方法,因为无论凭据是什么,测试总是通过的。
以下是我使用的代码:用途:

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。
知道了这一点,为什么我的测试总是通过,我如何纠正它以满足我的需要?

iyfjxgzm

iyfjxgzm1#

你需要通知mocha你正在编写的测试是mochc。在你的it函数调用中添加一个done回调,并从connection.connect调用这个done回调。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);
        });
    })
});

字符串

r8uurelv

r8uurelv2#

你需要安装MySQL。
用途:

npm install mysql

字符串
然后,像这样导入它:

const mysql = require('mysql');

相关问题