Wednesday, 7 June 2017

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

I'm writing small middleware for express.js route, but when I came to unit test this code I stuck, and I don't know how to properly test it using mocha, sinon and chai.

My middleware code has entrypoint something like this:

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 test if method searchByMarker or searchByQuerystring was called.

So I start with 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);
});

where my middleware should use searchByQuerystring for process request and I would like to test it if searchByQuerystring method was called, but I really don't know how to do that, maybe i just should write this code in some other way, I really don't want to use libraries like proxyquire .

Maybe my module is doing too much work (according to Single Responsibility Principle) - but whole middleware is for build search object where on start I just need to find out from which place parameters will came, so I thought that it is a good idea to put this logic on start of the middleware - and I just should have two middlewares?

Please for any help, suggestions about this.



via Ɓukasz Szewczak

No comments:

Post a Comment