简体   繁体   English

如何使用Mocha和Chai单元测试此node.js模块?

[英]How can I unit test this node.js module using mocha and chai?

I have this file containing the following code which is the database layer of my api. 我的文件包含以下代码,这是我的api的数据库层。 It is externally dependent on SQL Server to fetch the data. 它在外部依赖于SQL Server来获取数据。

var sql = require('mssql');
var async = require('async');

module.exports = {
    getDetails: function(number, callback) {

    async.parallel({
            general: function(callback) {
                getGeneral(number, callback);
            },
            preferences: function(callback) {
                getPref(number, callback);
            }
        },
        function(err, results) {
            if (err) {
                logger.error(err);
                throw err;
            }
            callback(results);
        });
}
};

function getGeneral(number, callback) {
    var mainconnection = new sql.Connection(dbCredentials[1].generalDBConfig, function(err) {
        var request = new sql.Request(mainconnection);
        request.input('number', sql.BigInt, number);
        request.execute('[number].[genral_get]', function(err, recordsets) {
            if (err) {
                logger.error(err);
            }
            var gen = {};
            var spResult = recordsets[0];
            if (spResult[0] != null) {
                spResult.forEach(function(record) {
                    var test = {};
                    gen[record.genCode] = record.genValue;
                });

                callback(null, gen);
            } else {
                callback(null, null);
            }

        });

    });
}

function getPref(number, callback) {
    var mainconnection = new sql.Connection(dbCredentials[0].prefDBConfig, function(err) {
        var request = new sql.Request(mainconnection);
        request.input('number', sql.BigInt, number);
        request.execute('[number].[pref_get]', function(err, recordsets) {
            if (err) {
                logger.error(err);
            }
            var spResult = recordsets[0];
            if (spResult[0] != null) {
                callback(null, spResult[0]);
            } else {
                callback(null, null);
            }

        });

    });
}

The database layer return this JSON format data: 数据库层返回此JSON格式的数据:

{
                        "general": {
                            "number": "72720604"
                            "title": "Mr  ",
                            "buildingNameNumber": null,
                            "subBuildingName": null,
                            "streetName": null,
                            "postalTown": null,
                            "county": null
                        },
                        "pref": {
                            "UseAccessibilitySite": "00000",
                            "IntroductorySource": "75"
                        }
                    };

As I am new to unit testing, I don't know how to start about writing unit tests for this module even though choosing mocha with chai as my unit testing framework. 由于我是单元测试的新手,即使选择带有chai的mocha作为我的单元测试框架,我也不知道如何开始为此模块编写单元测试。 Any kind of suggestions or help is appreciated... 任何形式的建议或帮助都将受到赞赏...

The question is: what exactly do you want to test in this code? 问题是:您到底要在此代码中测试什么?

I'm assuming that the answer roughly is "I want to call getDetails() in my test suite and verify that it behaves correctly". 我假设答案大致是“我想在测试套件中调用getDetails()并验证其行为正确”。

Of course, you don't want to create a whole MSSQL server in your test suite. 当然,您不想在测试套件中创建整个MSSQL服务器。 Instead, it's much easier to stub the database. 相反, 存根数据库要容易得多。

A module for mocking, stubbing and spying that I've had great success with is sinon.js . 我曾获得巨大成功的用于模拟 ,存根和监视的模块是sinon.js For your code, you'll need to stub a few things: 对于您的代码,您需要添加一些内容:

  • Stub sql.Connection() to return a stubbed connection object. 存根sql.Connection()返回存根的连接对象。
  • Stub sql.Request() to return a stub object that has methods input and execute . 存根sql.Request()返回具有inputexecute方法的存根对象。
  • Stub sql.BigInt() to verify that it was called correctly. 存根sql.BigInt()以验证它是否被正确调用。

Then, for the stubbed request object, you need to: 然后,对于存根request对象,您需要:

  • Verify that .input() was called correctly. 验证.input()是否被正确调用。
  • Make sure that execute returns the record(s) of your choosing. 确保execute返回您选择的记录。

It will be a lot of setup work to test the getDetails() function entirely. 完全测试getDetails()函数将需要大量的设置工作。 You might also be interested in the rewire module, which allows you to test getGeneral() and getPref() directly without having to add them to module.exports . 您可能也有兴趣的中联控模块,使您可以测试getGeneral()getPref()直接,而无需将其添加到module.exports

Finally, refactoring this code into smaller pieces will also help a lot. 最后,将此代码重构为较小的部分也将很有帮助。 For example, if you could do something like this: 例如,如果您可以执行以下操作:

// This is your own db module, which takes care of connecting
// to the database for you.
var db = require('./db');

function getGeneral(number, callback) {
    var request = db.createRequest();
    // The rest of the function
}

Then it would be much easier to use sinon to create a fake request object that does exactly what you want it to do. 这样,使用sinon创建一个完全可以执行您想要的操作的伪请求对象会容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Chai、Sinon、Mocha 在 Node.js 中测试控制器 - How to test a controller in Node.js using Chai, Sinon, Mocha 如何使用Mocha单元测试node.js功能? - How can I unit test node.js functions with Mocha? 使用Mocha,Chai和Sinon对Node.js应用程序进行单元测试 - Unit Test a Node.js application with Mocha, Chai, and Sinon 单元测试 node.js mongoose mocha chai sinon - unit test node.js mongoose mocha chai sinon 如何在异步等待中强制通过测试用例 Node.js 使用 Chai 和 mocha 的单元测试代码 - How to pass test-case forcibly in Async await Node.js Unit Testing code using Chai and mocha 使用 Mocha、sinon 和 chai 进行 Node.js axios 单元测试 - Node.js axios unit testing using Mocha, sinon and chai 使用 mocha chai 测试 node.js 中引发的错误 - test for error thrown in node.js using mocha chai 如何使用Mocha和Chai测试没有终点的Node模块 - How to test Node module with no end points using mocha and chai 如何在 Node.js 应用程序上使用相互 SSL 和测试框架 Mocha/Chai(chai-http) - How to use mutual SSL with test framework Mocha/Chai(chai-http) on a Node.js application 使用express,node.js构建的restful api的单元测试记录(使用mocha,supertest和chai) - Unit test logging (use mocha, supertest, and chai) of restful api built with express, node.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM