我想测试下面的代码,但我不确定如何测试这个函数,因为它返回一个带参数的函数。您可以在图像中看到我正在尝试实现 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
})
最佳答案
对于这种测试,我们可以做的是监视 jwt 函数调用并检查其参数。
更新:
由于 express-jwt
返回函数,我们需要涉及 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
})
希望对你有帮助
关于javascript - 如何测试返回带参数的函数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51489064/