Is there any way to test such middleware in express:
module.exports = function logMatchingUrls(pattern) { return function (req, res, next) { if (pattern.test(req.url)) { console.log('request url', req.url); req.didSomething = true; } next(); } }
The only test testing I found was:
module.exports = function(request, response, next) { /* * Do something to REQUEST or RESPONSE **/ if (!request.didSomething) { console.log("dsdsd"); request.didSomething = true; next(); } else { // Something went wrong, throw and error var error = new Error(); error.message = 'Error doing what this does' next(error); } }; describe('Middleware test', function(){ context('Valid arguments are passed', function() { beforeEach(function(done) { /* * before each test, reset the REQUEST and RESPONSE variables * to be send into the middle ware **/ requests = httpMocks.createRequest({ method: 'GET', url: '/css/main.css', query: { myid: '312' } }); responses = httpMocks.createResponse(); done(); // call done so that the next test can run }); it('does something', function(done) { /* * Middleware expects to be passed 3 arguments: request, response, and next. * We are going to be manually passing REQUEST and RESPONSE into the middleware * and create an function callback for next in which we run our tests **/ middleware(responses, responses, function next(error) { /* * Usually, we do not pass anything into next except for errors, so because * in this test we are passing valid data in REQUEST we should not get an * error to be passed in. **/ if (error) { throw new Error('Expected not to receive an error'); } // Other Tests Against request and response if (!responses.didSomething) { throw new Error('Expected something to be done'); } done(); // call done so we can run the next test }); // close middleware }); // close it }); // close context }); // close describe
This works well with simple middleware (it, like testing the base function with a callback) described above, but with more complex middleware, I can't get it to work. Is it possible to test this middleware?
Aaleks
source share