开玩笑-无法设置假Cookie

时间:2020-09-15 22:45:10

标签: javascript node.js typescript unit-testing jestjs

我非常感谢您的帮助。

我正在尝试设置伪造的cookie,以向需要身份验证的路由发出进一步的TEST请求。 但是请求显示request payloadundefined

setup.ts中的JEST模拟身份验证实现:

global.signin = (user: string): string[] => {
  const payload = {
    id: user || new mongoose.Types.ObjectId().toHexString(),
    email: 'test@test.com'
  };
  const token = jwt.sign(payload, process.env.JWT_KEY!); // key defined above in beforeAll()
  const session = { jwt: token };
  const sessionJSON = JSON.stringify(session);
  const base64 = Buffer.from(sessionJSON).toString('base64');
  return [`express:sess=${base64}`];
};

JEST测试实施:

it('returns 201 if updated after authentication', async () => {
  const user = User.build({
    firstName: 'first',
    lastName: 'last',
    email: 'test@test.com',
    id: '5f60f5d43efc838dd629ce16'
  })
  await user.save();
  const profile = await Profile.findOne({
    user: user.id
  })
  expect(profile).not.toEqual(null)
  const response = await request(app)
    .post('/api/profile/' + profile!.id)
    .set('Cookie', global.signin(profile!.user))
    .send({
      about: 'This is some random text',
      picture: 'http://example.com'
    })
    .expect(201)
})

API路径:

router.post('/api/profile/:id', [
  body('about').isLength({ max: 300 })
], currentUser, authenticate, validateRequest, async (req: Request, res: Response) => {
  const profile = await Profile.findById(req.params.id);
  // tests 
  if (!profile) {
    throw new BadRequestError('Profile not found');
  }
  if (profile.user !== req.currentUser!.id) { // <== Throws error cannot read id of undefined 
    throw new NotAuthorizedError();     
  }

中间件没什么问题,因为通过Postman测试时,它们可以与其他路由正常工作。

谢谢。

0 个答案:

没有答案