NodeJS chai.request.agent不会在请求之间保持cookie

mccptt67  于 2023-06-29  发布在  Node.js
关注(0)|答案(1)|浏览(156)

我在使用Chai. request. agent时遇到了一个奇怪的问题。下面是我的测试代码:

const chai = require("chai");
const chaiHttp = require("chai-http");
chai.use(chaiHttp);
let agent;

beforeEach(() => {
  agent = chai.request.agent(app);
});

afterEach(() => {
  agent.close();
});

it("should do something", async () => {
  //Log in
  const res = await agent.post("/api/my-endpoint").send(userDetails);

  expect(res).to.have.cookie("my-cookie");

  //Test endpoint
  const res2 = await agent.get("/api/my-other-endpoint");
  expect(res2).to.have.status(200);
});

第二个请求被发送到一个端点,该端点检查my-cookie是否存在,如果不存在则返回401,如果存在则返回200。我在这里得到了一个401,我知道这是由于缺少my-cookie作为控制台而触发的。
下面是端点代码:

router.post("/my-endpoint", async function (req, res) {
try {
    const token = jwt.sign(
      { id: 4 },
      process.env.SECRET,
      { expiresIn: "12h" }
    );

    res.cookie("my-cookie", token, {
      httpOnly: true,
      maxAge: 60 * 60 * 12 * 1000,
      secure: true,
      sameSite: "strict",
    });

    res.sendStatus(200);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "ERROR: log in failed" });
  }
});

router.get("/my-other-endpoint", async function (req, res) {
  try {
    const cookies = req.cookies;

    if (!cookies?.my-cookie) {
      console.log("No cookie"); //This gets logged
      return res.sendStatus(401);

    } else {
      res.sendStatus(204);
    }
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "ERROR" });
  }
});

我试过从文档中复制Promise链接的例子,但是当我使用这种方法时,第二个请求没有运行

pw9qyyiw

pw9qyyiw1#

secure选项设置为false或取消设置。
app.js

const express = require('express');
const cookieParser = require('cookie-parser');

const app = express();

app.use(cookieParser());
app.post('/my-endpoint', function (req, res) {
  res
    .cookie('my-cookie', 'abc123', {
      httpOnly: true,
      maxAge: 60 * 60 * 12 * 1000,
      // secure: true,
      sameSite: 'strict',
    })
    .sendStatus(200);
});

app.get('/my-other-endpoint', function (req, res) {
  console.log('my-cookie: ', req.cookies['my-cookie']);
  if (!req.cookies['my-cookie']) {
    console.log('No cookie');
    res.sendStatus(401);
  } else {
    res.sendStatus(204);
  }
});

module.exports = app;

app.test.js

const chai = require('chai');
const chaiHttp = require('chai-http');
const app = require('./app');

chai.use(chaiHttp);
const { expect } = chai;

let agent;

beforeEach(() => {
  agent = chai.request.agent(app);
});

afterEach(() => {
  agent.close();
});

it('should do something', async () => {
  const res = await agent.post('/my-endpoint').send({});
  expect(res).to.have.cookie('my-cookie');
  const res2 = await agent.get('/my-other-endpoint');
  expect(res2).to.have.status(204);
});

测试结果:

my-cookie:  abc123
  ✓ should do something

  1 passing (18ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   84.61 |       50 |     100 |   84.61 |                   
 app.js   |   84.61 |       50 |     100 |   84.61 | 21-22             
----------|---------|----------|---------|---------|-------------------

相关问题