如何使用 mocha/chai 设置 jwt cookie?

How to set a jwt cookie with mocha/chai?

我需要用 mocha 和 chai 测试受保护的路由。身份验证中间件一直崩溃并出现错误 500,因为 jwt must be a string.

当用户登录时,他会收到一个仅包含 http 的 cookie,其数据是一个 jwt 令牌。由于 axios withCredentials: true 属性.

,cookie 会在每次请求时自动发送到服务器

因此,我尝试为我的测试设置一个 cookie 或 auth 承载,但到目前为止没有任何成功。如何解决这个问题?

这是我写的:

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 路线。任何帮助将不胜感激。

req.cookies是一个对象,来自express docs:

When using cookie-parser middleware, this property is an object that contains cookies sent by the request. If the request contains no cookies, it defaults to {}.

所以需要这样设置cookie里面的jwt:

.set('Cookie', `jwtToken=${token}`)

并在您的中间件中获取它:

const { jwtToken } = req.cookies;
jwt.verify(jwtToken, ...