我们的后端(Node)和我们的前端(React)分别托管在GCP和Heroku上。
我们正在努力将自动化测试添加到我们的后端代码中,但是由于我们的所有路由都是使用Firebase进行身份验证的,因此我们不确定如何测试经过身份验证的路由。具体来说,我们在前端有Firebase Client,在后端有Firebase Admin。
我们的测试框架目前使用Jest和Supertest。我们已经尝试使用firebase-mock程序包对其进行测试,但这并没有真正起作用。因为即使传递模拟令牌,我们也总是得到400响应。
这是我们的collect()
中间件的代码:
auth
这是我们的// This middleware will verify that a request is coming from an authorized user
const admin = require('firebase-admin')
module.exports = async function auth(req, res, next) {
// Try to extract the firebase-auth-token from the request header,
// respond with access denied if firebase-auth-token is not found
const token = req.header('x-auth-token')
if (!token) res.status(401).send('Access denied. No auth token provided.')
try {
const decodedToken = await admin.auth().verifyIdToken(token)
req.user = { ...decodedToken }
next()
} catch (ex) {
// Respond with 'bad request' if the token is invalid
res.status(400).send('Invalid token.')
}
}
文件的代码:
auth.test.js