How to test a node.js module that returns an anonymous function?

I write a little middleware for the express.js route, but when I came to unit test for this code, I got stuck and I don’t know how to test it correctly using mocha, sine and chai.

My intermediate code has an entry point something like this:

 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();
   }
};

and during unit test I would like to check if the searchByMarker or searchByQuerystring method was called .

So, I start by writing this test,

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.

, ( ), , , , , - ?

, , .

+4
1

,

, , . , .

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');
});

, searchByMarker searchByQuerystring searchRequestParser , , , , out searchByMarker searchByQuerystring.

, , / .

0

Source: https://habr.com/ru/post/1678736/


All Articles