我创建了这个中间件,当 queryItems
定义路由的唯一参数时,它将返回 next()
。
我最近发现node-mocks-http其中 fakes 表示 req
和 res
对象。但它不会伪造 next
。我想知道应该怎么做?下面是我打开 next
回调并在其中定义我的 expect
语句的示例。
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")
}
}
这是测试。
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()
})
})
这是执行此操作的正确方法吗?有什么方法可以让这个更简单/更容易,也许将其转换为 promise ,这样我就可以使用 chai-as-promised?
Note: _.hasOnly is a custom underscore mixin.
最佳答案
我喜欢Sinon对于这样的测试:
// first test
...
var res = httpMocks.createResponse()
var spy = sinon.spy();
middleware.hasOnlyQuery(["foo"])(req, res, spy);
expect(spy.calledWithExactly()).to.be.true;
// second test
...
expect(spy.calledWithExactly('route')).to.be.true;
关于javascript - 测试返回 next()/next ("route"的快速中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31308587/