我目前正在对我的所有路线进行单元测试,包括使用自定义护照身份验证功能的路线。我正在尝试模拟通行证功能以测试错误处理,但是我不断收到错误:
TypeError: _passport.default.authenticate(...) is not a function
这是在/controllers/users.js
中运行的实际代码:
export const persistentLogin = (req, res, next) => {
// Authenicate the cookie sent on the req object.
passport.authenticate('jwt', { session: false }, async (authErr, user) => {
// If there is an system error, send 500 error
if (authErr) return res.sendStatus(500);
// If no user is returned, send response showing failure.
if (!user) {
return res.status(200).json({
success: 'false',
});
}
})(req, res, next);
};
这是/tests/controllers/users.js
中的测试代码:
import passport from 'passport';
import { persistentLogin } from '../../controllers/users';
beforeEach(() => {
mockResponse = () => {
const response = {};
response.status = jest.fn().mockReturnValue(response);
response.json = jest.fn().mockReturnValue(response);
response.sendStatus = jest.fn().mockReturnValue(response);
response.clearCookie = jest.fn().mockReturnValue(response);
response.cookie = jest.fn().mockReturnValue(response);
return response;
};
});
/**
* persistentLogin Tests
*/
describe('Persistent Login Controller', () => {
beforeEach(() => {
req = {};
res = mockResponse();
validateLoginForm.mockClear();
bcrypt.compare.mockClear();
});
// Passport authenication error
test('Should show passport authenication error', async () => {
passport.authenticate = jest.fn((authType, options, callback) => callback('This is an error', null));
await persistentLogin(req, res);
expect(passport.authenticate).toHaveBeenCalledTimes(1);
expect(res.sendStatus).toHaveBeenCalledWith(500);
});
});
如果我不得不猜测,我会说这与事实之后将(req,res,next)对象如何传递到实时函数有关。但是由于我们只是在模拟该函数,所以我不确定它是否真的需要访问那些对象。
编辑#1:
根据@jakemingolla的评论,我现在想这可能是因为Jest没有运行定义我的自定义JWT策略的app.js文件。
这是/app.js
文件中的代码:
import passport from 'passport';
import passportJWTStrategy from './utils/auth/passport';
app.use(passport.initialize());
passportJWTStrategy(passport);
还有/utils/auth/passport.js
文件中的代码:
import { Strategy } from 'passport-jwt';
/**
* Verifies JWT payload
*
* @param passport The instance of passport module.
*/
export default (passport) => {
const JWTStrategy = Strategy;
// Setup Options Object
const opts = {};
opts.jwtFromRequest = req => req.cookies.jwt;
opts.secretOrKey = process.env.PASSPORT_SECRET;
passport.use(
new JWTStrategy(opts, (jwtPayload, done) => {
if (Date.now() > jwtPayload.expire_date) {
return done('jwt expired');
}
return done(null, jwtPayload);
}),
);
};