繁体   English   中英

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

[英]How to test node.js module which returns anonymous function?

我正在为express.js路由编写小型中间件,但是当我来测试这个代码时,我卡住了,我不知道如何使用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方法我想测试它,但我真的不知道怎么做,也许我应该用其他方式编写这个代码,我真的不喜欢我想使用像proxyquire这样的

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

请提供任何帮助,建议。

好的,

所以把这篇文章帮我找到解决方案。 我重写了我的中间件入口点,看起来像这样

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中重复的

感谢我使用的函数的返回输出,我不必专注于模拟/存根这些函数。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM