node.js - 如何对池连接进行单元测试?

标签 node.js unit-testing mocha.js chai node-mysql

我想在我的 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/

相关文章:

javascript - 使用 Sinon.js 创建模拟时,mock.restore() 实际上做了什么?

javascript - MongoDB 创建用于测试的数据库

javascript - Sails.js:如何实际运行测试

javascript - Angular2 - 在客户端需要模块

node.js - 升级前如何查看 npm 包的发行说明?

java - 用于自动化测试脚本的 JUnit 测试?

angular - Marble 测试 rxjs 在 Angular 服务上可观察到

unit-testing - 可以在 Controller 的show()方法中使用模拟域 “instance”吗?

javascript - 当服务器关闭/崩溃时,Node JS 自动重启所有永远的 JS 进程

node.js - 如何使 NodeJS Passport session 保持事件状态