Mocha/Node.js/PostgreSQL集成测试

Mocha/Node.js/PostgreSQL integration testing

本文关键字:集成测试 PostgreSQL Node Mocha js      更新时间:2023-09-26

我已经尝试了好几天了。我在互联网和StackOverflow上查过了。有一些例子说明如何使用MongoDB测试api,以及如何编写执行PSQL命令的Mocha测试。那不是我想要的。

我为pg创建了一个包装器,从这个SO问题中的指令中称为db.js(请注意我在调用console.log()时的注释:

pg = require("pg");
config = require("./../config.js");
module.exports = { 
    query: function(text, values, cb) {
        console.log("I get to this in Mocha");
        pg.connect(config.connectionString, function(err, client, done) {
            console.log("I never get here");
            if (err) return console.error("error connecting to postgres: ", err);
            client.query(text, values, function(err, result) {
                console.log("I most certainly never get here");
                done();
                cb(err, result);
            })
        });
    }
}

有了这个,我可以做以下事情:

$ node
$ var db = require ("./path/to/db.js");
$ db.query("insert into sometable(id, value) values(1, '"blah'")", {}, function (err, result) {
            if (err) { console.error ("db errored out man"); }
            console.log("no error...");
            console.log(result);
        });

信不信由你,工作得很顺利!

我不能在mocha测试(即db.spec.js)中做同样的事情:

var db = require("./../../../Data/db.js");
// These tests assume you have run the scripts in the -SQL repo
describe("module: db", function() {
    it("provides a wrapper for the execution of queries", function () {
        db.query("insert into employer.profile '
            (id, returncustomer, receiveupdates, name, email, password, active) '
            values (4, true, true, 'someNameLol', 'ce@spam.org', 'change_me', true)", {}, 
            function (err, stdout, stderr) { 
                console.log(err || ""); 
                console.log(stdout || ""); 
                console.log(stderr || ""); 
            }
        );
    });
}); 

帮助!我希望能够使用我的数据库连接编写集成测试。我是否遗漏了某些组件?必需的库?

这些都是手工制作的,我没有使用IDE,因为我想自己了解它应该如何工作。

您需要包含done参数,并在测试结束时调用它。

describe("module: db", function() {
    it("provides a wrapper for the execution of queries", function (done) {
        db.query("insert into employer.profile '
            (id, returncustomer, receiveupdates, name, email, password, active) '
            values (4, true, true, 'someNameLol', 'ce@spam.org', 'change_me', true)", {}, 
            function (err, stdout, stderr) { 
                console.log(err || ""); 
                console.log(stdout || ""); 
                console.log(stderr || ""); 
                done();
            }
        );
    });
});