admin管理员组

文章数量:1427989

Hi I am testing to see if it authorizes me to get orders. Currently BeforeAll is reading the token but I still receive 401 when I run my test. What is going wrong in my code? I am using Jest and Supertest.

This is my test file.

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

let token 

beforeAll((done) => {
    request(app)
        .post('/api/users/login')
        .send({
            email: '[email protected]',
            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);
                })
        });
    }); 
}); 

I save the token beforehand then I run my test. I've looked everywhere but can't seem to find a solution.

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

Hi I am testing to see if it authorizes me to get orders. Currently BeforeAll is reading the token but I still receive 401 when I run my test. What is going wrong in my code? I am using Jest and Supertest.

This is my test file.

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

let token 

beforeAll((done) => {
    request(app)
        .post('/api/users/login')
        .send({
            email: '[email protected]',
            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);
                })
        });
    }); 
}); 

I save the token beforehand then I run my test. I've looked everywhere but can't seem to find a solution.

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')
    }
})
Share Improve this question edited Mar 7, 2021 at 6:26 dmart14 asked Mar 6, 2021 at 9:56 dmart14dmart14 412 silver badges7 bronze badges 12
  • Why it should return http status 200? – hoangdv Commented Mar 6, 2021 at 12:24
  • @hoangdv 401 is unauthorized and 200 is ok – dmart14 Commented Mar 6, 2021 at 19:21
  • Your server requires an access token to access to /api/orders resource. – hoangdv Commented Mar 7, 2021 at 1:50
  • Well, I am currently returning a token. BeforeAll is returning a token and saving it to the variable token. I then use it in my unit test and call token again with Bearer but it still fails – dmart14 Commented Mar 7, 2021 at 3:10
  • Are you sure token variable has value? – hoangdv Commented Mar 7, 2021 at 3:31
 |  Show 7 more ments

1 Answer 1

Reset to default 3

As long as you only need to test if response is ok, instead of using Jest expect, did you try using the expect from superset? something like:

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

本文标签: javascriptJest testing API Expect 200 but received 401Stack Overflow