简体   繁体   English

Node.Js - Jest 测试(令牌问题得到 401“未经授权”)

[英]Node.Js - Jest Testing (Token Problem got 401 "Unauthorized")

Hello I'm testing with Jest a project with Node.js I want to test my functions你好,我正在用 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)

}) })

but I got this error :但我收到了这个错误:

 ● 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)

Do you get 200 for that endpoint in a REST client with the same Auth token?您是否在具有相同身份验证令牌的 REST 客户端中为该端点获得 200? 401 "Unauthorized" would mean the token is invalid. 401“未授权”意味着令牌无效。 So you need to check your token.所以你需要检查你的令牌。 If there is nothing wrong with the token, try below如果令牌没有问题,请尝试以下

I believe the request is a require of supertest?我相信这个要求是 supertest 的要求?

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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM