如何测试带参数的 returns 函数?

How to test function which returns function with parameters?

我想测试下面的代码,但我不确定如何测试这个函数,因为它 returns 是一个带参数的函数。您可以在图像中看到我正在尝试实现 100% 的测试覆盖率,为此我需要一个进入返回函数的测试。

const jwt = require('express-jwt')

function validateJwt (tokenConfig) {
  if (!tokenConfig || !tokenConfig.secret) {
    throw new TypeError('tokenConfig param must be defined and have attribute "secret"')
  }

  return (req, res, next) => {
    jwt(_.extend({}, tokenConfig, {
      requestProperty: 'tkn',
      getToken: ReqHelpers.getEitherTkn
    }))
  }
}

明显失败并出现错误的测试方法AssertionError: expected [Function] to be true

it('should succeed', () => {
  let result = middleware.validateJwt({secret: 'foo'})
  expect(result).to.be.true
})

对,所以有两件事。

首先,在您的测试中您需要执行 returned 函数而不是直接测试它。不幸的是,我正在 phone 上,现在无法 post 编码。

其次,您 returned 的函数本身不会 return 任何东西,因为它只是调用 jwt 函数。这不一定是个问题。只要 jwt() 正在更新测试 space 中的某些对象或变量,您就可以在测试中测试 obj/variable 的当前状态,而不是直接询问函数。

对于这种测试,我们可以做的是监视 jwt 函数调用并检查其参数。

更新:

由于express-jwtreturn函数,我们需要涉及proxyquire来窥探该函数。参考:https://github.com/thlorenz/proxyquire

你可以这样做:

const proxyquire = require('proxyquire');
const sinon = require('sinon');

const jwtSpy = sinon.spy();
const middleware = proxyquire('./middleware', { 'express-jwt': jwtSpy }); // 'express-jwt' comes from your require statement for this package

it('should call jwt', () => {
  const req = sinon.spy();
  const res = sinon.spy();
  const next = sinon.spy();  

  middleware.validateJwt({secret: 'foo'})(req, res, next);

  expect(jwtSpy.called).to.be.ok;
  expect(jwtSpy.calledWithArg({ secret: 'foo', requestProperty: 'tkn'}).to.be.ok; // for checking the arguments
})

希望对您有所帮助