首页 > 解决方案 > 开玩笑测试 API 期望 200 但收到 401

问题描述

嗨,我正在测试它是否授权我获得订单。目前 BeforeAll 正在读取令牌,但我在运行测试时仍然收到 401。我的代码出了什么问题?我正在使用 Jest 和 Supertest。

这是我的测试文件。

import app from '../server' 
import request from 'supertest'
jest.useFakeTimers()

let token 

beforeAll((done) => {
    request(app)
        .post('/api/users/login')
        .send({
            email: 'test15@email.com',
            password: '123456'
        })
        .end((err, response) => {
            token = response.body.token; // saving token 
            done();
        });
});


describe('app', () => {

    describe('Statuses', () => {
        it('Index should return 200 Status', () => {
           return request(app)
                .get('/api/orders')
                .set('Authorization', `Bearer ${token}`)
                .then((response) => {
                 expect(response.statusCode).toBe(200);
                })
        });
    }); 
}); 

我事先保存了令牌,然后运行我的测试。我到处寻找,但似乎找不到解决方案。

auth.js

const protect = asyncHandler(async(req,res,next) => {
    let token 
    if(
        req.headers.authorization && 
        req.headers.authorization.startsWith('Bearer')
    ){
        console.log('token found')
    }{
        try {
            token = req.headers.authorization.split(' ')[1]
            const decoded = jwt.verify(token, process.env.JWT_SECRET)
            req.user= await User.findById(decoded.id).select('-password')

            next()
        } catch (error) {
            console.error(error)
            res.status(401)
            throw new Error('Not authorized, token failed')
        }
    }

    if (!token){
        res.status(401)
        throw new Error('Not Authorized, no token')
    }
})

标签: javascriptnode.jsjestjssupertest

解决方案


只要您只需要测试响应是否正常,而不是使用 Jest expect,您是否尝试使用expectfrom superset?就像是:

it('should return 200 Status', () => {
  request(app)
    .get('/api/orders')
    .set('Authorization', `Bearer ${token}`)
    .expect(200, done);
});

推荐阅读