Javascript 如何测试返回匿名函数的node.js模块?

Javascript 如何测试返回匿名函数的node.js模块?,javascript,node.js,unit-testing,express,Javascript,Node.js,Unit Testing,Express,我正在为express.js route编写小型中间件,但当我开始单元测试这段代码时,我卡住了,我不知道如何使用mocha、sinon和chai正确地测试它 我的中间件代码的入口点如下: const searchByQuerystring = require('./search-by-querystring'); const searchByMarker = require('./search-by-marker'); module.exports = (req, res, next)

我正在为express.js route编写小型中间件,但当我开始单元测试这段代码时,我卡住了,我不知道如何使用mocha、sinon和chai正确地测试它

我的中间件代码的入口点如下:

 const searchByQuerystring = require('./search-by-querystring');
 const searchByMarker = require('./search-by-marker');

 module.exports = (req, res, next) => {

   if (req.marker) {
      searchByMarker(req, res, next);
   } else if (req.query) {
      searchByQuerystring(req, res, next);
   } else {
      next();
   }
};
,在单元测试期间,我想测试是否调用了方法searchByMarkersearchByQuerystring

所以我从写这个测试开始

it('Should call search by querystring if querystring is present', () => {
    const req = httpMocks.createRequest({
            query: {
                value: 1000
            }
        }),
        res = httpMocks.createResponse(),
        next = sandbox.spy();
    searchIndex(req, res, next);

    sinon.assert.calledOnce(next);
});
我的中间件应该在流程请求中使用searchByQuerystring,我想测试一下是否调用了searchByQuerystring方法,但我真的不知道如何做到这一点,也许我应该以其他方式编写此代码,我真的不想使用这样的库

也许我的模块做了太多的工作(根据单一责任原则),但整个中间件是用于构建搜索对象的,在开始时,我只需要找出参数将来自哪个地方,所以我认为在中间件开始时使用此逻辑是一个好主意-我应该有两个中间件

请提供任何帮助和建议。

好的

所以写这篇文章帮助我找到一个解决方案。我重写了我的中间件入口点,如下所示

const searchRequestParser = require('./search-request-parser');
const search = require('../../../lib/search');

module.exports = (req, res, next) => {

  const searchRequest = searchRequestParser(req);
  if (searchRequest) {
    const searchCriteria = search(searchRequest.resourceToSearch);
    req.searchQuery = 
  searchCriteria.buildQuery(searchRequest.queryParameters);
  }
  next();
};
和测试

    it('Should call search by querystring if querystring is present', () => {
    const req = httpMocks.createRequest({
            method: 'GET',
            params: {
                resourceToSearch: 'debts'
            },
            query: {
                value: 1000
            }
        }),
        res = httpMocks.createResponse(),
        next = sandbox.spy();
    searchIndex(req, res, next);

    expect(req).to.have.a.property('searchQuery');
});
因此方法searchByMarkersearchByQuerystring都消失了,取而代之的是方法searchRequestParser,并带有输出,然后我用代码处理这个输出,结果是以前在方法searchByMarkersearchByQuerystring中重复的


多亏了我使用的函数返回的输出,我不必把重点放在模拟/存根这些函数上。

除非您试图测试的函数可以通过某种方式访问,或者您可以根据输出验证调用了哪个函数,您最好的选择可能是依赖代码覆盖率工具,如。谢谢@msdex的建议!