我想在我的 Node.js 应用程序中对池连接 (mysql) 进行单元测试(mocha 和 chai)。我不知道我是否以正确的方式使用测试,如果是的话,为什么它们总是被限定为“待处理”。
给出以下代码,我将如何测试它?
var pool = mysql.createPool({
connectionLimit: 100,
host: 'localhost',
user: 'userName',
password: 'userPass',
database: 'userDatabase',
debug: false
});
我尝试了很多方法,但似乎不起作用。我得到的最好的是:
describe("Database", function () {
describe("Connection", function () {
it("Should connect without an error", pool.getConnection(function (err, connection) {
expect(err).to.be.null;
})
);
})
});
如果凭据正确,将返回:
Express server listening on port 8080
Database
Connection
- Should connect without an error
0 passing (15ms)
1 pending
如果凭据不正确,则返回:
Express server listening on port 8080
Database
Connection
- Should connect without an error
1) Uncaught error outside test suite
0 passing (23ms)
1 pending
1 failing
1) Database Connection Uncaught error outside test suite:
Uncaught AssertionError: expected [Error: ER_DBACCESS_DENIED_ERROR: Access denied for user 'userName'@'localhost' to database 'userDatabase'] to be null
提前谢谢您。
最佳答案
您在第二个参数中传递给 it
的内容必须是一个函数。现在你正在做:
it("Should connect without an error", pool.getConnection(...))
pool.getConnection
接受回调,因此很可能返回 undefined
。所以对于 Mocha 来说它看起来像这样:
it("Should connect without an error", undefined)
这是一个挂起的测试,因为回调的 undefined
是告诉 Mocha 测试正在挂起的方式。您需要将对 pool.getConnection
的调用包装在函数中:
it("Should connect without an error", function (done) {
pool.getConnection(function (err, connection) {
if (err) {
done(err); // Mocha will report the error passed here.
return;
}
// Any possible tests on `connection` go here...
done();
});
});
关于node.js - 如何对池连接进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42439874/