【发布时间】:2021-07-01 08:48:43
【问题描述】:
我需要用 mocha 和 chai 测试受保护的路线。由于jwt must be a string,身份验证中间件一直崩溃并出现错误500。
当用户登录时,他会收到一个 http-only cookie,其数据是一个 jwt 令牌。由于 axios withCredentials: true 属性,cookie 会在每次请求时自动发送到服务器。
所以,我尝试为我的测试设置一个 cookie 或一个身份验证承载,但到目前为止没有任何成功。如何解决这个问题?
这是我写的:
import chai from "chai";
import chaiHttp from "chai-http";
import { app } from "../index";
import jwt from "jsonwebtoken";
chai.use(chaiHttp);
const api = chai.request(app).keepOpen();
const token = jwt.sign(
{ _id: "123", locale: "en" },
process.env.JWT_TOKEN_KEY,
{
expiresIn: "14d",
}
);
describe("GET /user/:id", () => {
it("return user information", (done) => {
api
.get("/user/123")
.set("Cookie", token)
.end((err, res) => {
chai.expect(res).to.have.status(200);
done();
});
});
});
中间件是:
import { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
import { Cookie } from "../models/Cookie";
interface Authenticate extends Request {
cookie: Cookie;
cookies: any;
}
const authenticate = (req: Authenticate, res: Response, next: NextFunction) => {
const token = req.cookies;
if (token) {
jwt.verify(token, process.env.JWT_TOKEN_KEY, (error, res) => {
if (error) {
return res.sendStatus(403);
}
req.cookie = { _id: res._id, locale: res.locale };
return next();
});
}
return res.sendStatus(401);
};
export default authenticate;
自 48 小时以来,我一直在测试我的 api 路由。任何帮助将不胜感激。
【问题讨论】: