After developing a middleware function that returns next()
if a route's parameters are defined by queryItems
, I came across a useful tool called node-mocks-http. However, it does not fake the next
object. This led me to explore how this can be achieved. Below is an example where I manipulate the next
callback and set my expect
statement inside it.
middleware.hasOnlyQuery = function(queryItems){
return function(req, res, next){
if(typeof queryItems == "string") queryItems = [queryItems]
if(_.hasOnly(req.query, queryItems)) return next()
return next("route")
}
}
Here are some tests for this functionality:
it("should only have shop query", function(done){
var req = httpMocks.createRequest({
method: 'GET',
query: {
foo: "bar"
}
});
var res = httpMocks.createResponse()
var fn = middleware.hasOnlyQuery(["foo"])(req, res, function(err){
expect(err).to.equal()
return done()
})
})
it("should not only have shop query", function(done){
var req = httpMocks.createRequest({
method: 'GET',
query: {
foo: "bar",
bar: "foo"
}
});
var res = httpMocks.createResponse()
var fn = middleware.hasOnlyQuery(["foo"])(req, res, function(err){
expect(err).to.equal("route")
return done()
})
})
I'm curious if there is a simpler or more efficient way to achieve this. Perhaps converting it into a promise so that I can utilize chai-as-promised?
Note: You can find the custom underscore mixin here.