0

我在使用 jest 和 supertest 测试 node.js API 中的端点时遇到问题。我正在尝试使用新的 jwt 令牌更新会话。会话结构如下所示:

req.session = {
  jwt: SOME_JWT_TOKEN
}

下面是在会话 (endpoint.ts) 上设置新令牌的代码:

const setUserPayload: THandler = async (
  req: Request,
  res: Response
): Promise<void> => {
  try {
    // Create payload
    userPayload = {
      id: SOME_ID,
    };

    // Convert payload to JWT
    const jwtUserPayload = jwt.sign(userPayload, process.env.JWT_SECRET!, {
      algorithm: 'HS256',
      expiresIn: '7 days',
    });

    // Store it on the session
    if (req.session && req.session.jwt) {
      req.session.jwt = jwtUserPayload;
    } else {
      throw new Error('jwt key is not defined on the session');
    }

    res.status(200).send({
      userPayload: userPayload,
    });
  } catch (e) {
    throw e;
  }
};

下面是查看是否设置了标头的测试代码(test.ts):

import request from 'supertest';
import { app } from '../config/app';
import jwt from 'jsonwebtoken';

it('sets cookie after updating the user payload with descriptive cookie', async () => {
  // Payload
  const payload: IUserPayload = {
    id,
    record: {
        id: 'abcd',
    },
    account: {
      email: 'test@test.com',
    },
  };

  // Cookie
  const token = jwt.sign(payload, process.env.JWT_SECRET!, {
    algorithm: 'HS256',
    expiresIn: '7 days',
  });
  const session = { jwt: token };
  const sessionJSON = JSON.stringify(session);
  const base64 = Buffer.from(sessionJSON).toString('base64');
  const cookie = [`express:sess=${base64}`];

  // Get updated cookie
  const response = await request(app)
    .get(`/api/profile/v1/current-user`)
    .set('Cookie', cookie)
    .expect(200);
  

  // Check the 'Set-Cookie' header
  expect(response.get('Set-Cookie')).toBeDefined();
});

奇怪的是,只要我没有设置 jwt 的到期时间(在 endpoint.ts 中),测试就可以正常工作。如果我删除 expiresIn,则测试通过。但是如果我设置 expiresIn 测试偶尔会通过(平均 1/6 次),否则测试会失败。

任何帮助或见解或希望将不胜感激。太感谢了!

更新:我发现如果我删除现有有效负载上的“iat”和“exp”属性并创建一个新的 cookie,它会起作用。

4

0 回答 0