【问题标题】:Node.Js - Jest Testing (Token Problem got 401 "Unauthorized")Node.Js - Jest 测试(令牌问题得到 401“未授权”)
【发布时间】:2021-02-04 22:41:18
【问题描述】:

您好,我正在用 Jest 测试一个使用 Node.js 的项目 我想测试我的功能

const userOne = {
_id: userOneId,
name: 'Mike',
email: 'mikey@example.com',
password: '56what!!',
tokens: [{
    token: jwt.sign({ _id: userOneId }, process.env.JWT_SECRET)
}] }

test('Should get profile for user', async () => {
await request(app)
    .get('/users/me')
    .set('Authorization', `Bearer ${userOne.tokens[0].token}`)
    .send()
    .expect(200)

})

但我收到了这个错误:

● Should get profile for user

expected 200 "OK", got 401 "Unauthorized"

  at Test.Object.<anonymous>.Test._assertStatus (node_modules/supertest/lib/test.js:270:12)
  at Test.Object.<anonymous>.Test._assertFunction (node_modules/supertest/lib/test.js:285:11)
  at Test.Object.<anonymous>.Test.assert (node_modules/supertest/lib/test.js:175:21)
  at Server.localAssert (node_modules/supertest/lib/test.js:133:12)

【问题讨论】:

    标签: javascript node.js jestjs jwt


    【解决方案1】:

    在具有相同身份验证令牌的 REST 客户端中,您是否为该端点获得 200? 401“未授权”表示令牌无效。所以你需要检查你的令牌。如果令牌没有问题,请在下面尝试

    我相信这个请求是超测的要求?

    const request = require('supertest');
    
    test('Should get profile for user', async () => {
    const response = await request(app)
                     .get('/users/me')
                     .set('Authorization', `Bearer ${userOne.tokens[0].token}`)
     expect(response.status).toEqual(200);
    });
    

    【讨论】:

      猜你喜欢
      • 2021-08-22
      • 2016-05-17
      • 2014-01-30
      • 1970-01-01
      • 2020-08-07
      • 2017-07-06
      • 2011-11-16
      • 2023-03-03
      • 1970-01-01
      相关资源
      最近更新 更多