测试表示返回next()/ next(“route”)的中间件

时间:2015-07-09 05:06:50

标签: javascript unit-testing express mocha middleware

我创建了这个中间件,当路由的唯一参数由next()定义时,它将返回queryItems

我最近发现node-mocks-http假货表达reqres个对象。但它不会伪造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()
  })
})

这是正确的方法吗?有没有办法让这更简单/更容易,也许可以将它转换为承诺,以便我可以使用chai-as-promised?

  

注意:_.hasOnly是自定义下划线mixin。

3 个答案:

答案 0 :(得分:1)

我喜欢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;

答案 1 :(得分:0)

使这种更平滑的一种方法是创建“下一个可以有的三种响应。”

function nextNormal(done){
  return function(err){
    expect(err).to.equal(undefined)
    return done()
  }
}

function nextRoute(done){
  return function(err){
    expect(err).to.equal("route")
    return done()
  }
}

function nextError(done){
  return function(err){
    expect(err).to.be.an('object')
    return done()
  }
}

然后你可以在一行中使用它

middleware.hasOnlyQuery(["foo", "bar"])(req, res, nextNormal(done))

答案 2 :(得分:0)

将中间件转换为与express-promise-router一起使用的承诺。

middleware.hasOnlyQuery = function(queryItems){
  return function(req, res){
    if(typeof queryItems == "string") queryItems = [queryItems]
    if(_.hasOnly(req.query, queryItems)) return Promise.resolve('next')
    return Promise.resolve('route')
  }
}

使用chai-as-promisedbluebird的新测试:

it("should fire correct next callback", function(done){
  Promise.all([
    middleware.hasOnlyQuery(["foo"])(reqFoo, res).should.eventually.equal("next"),
    middleware.hasOnlyQuery(["foo", "bar"])(reqFoo, res).should.eventually.equal("route"),
    middleware.hasOnlyQuery(["foo", "alpha"])(reqFoo, res).should.eventually.equal("route"),
    middleware.hasOnlyQuery(["foo"])(reqFooBar, res).should.eventually.equal("route"),
    middleware.hasOnlyQuery(["foo", "bar"])(reqFooBar, res).should.eventually.equal("next"),
    middleware.hasOnlyQuery(["foo", "alpha"])(reqFooBar, res).should.eventually.equal("route")
  ]).then(function(){
    done()
  })
})