javascript - 开玩笑测试 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')
}
})
解决方案
只要您只需要测试响应是否正常,而不是使用 Jest expect
,您是否尝试使用expect
from superset
?就像是:
it('should return 200 Status', () => {
request(app)
.get('/api/orders')
.set('Authorization', `Bearer ${token}`)
.expect(200, done);
});
推荐阅读
- java - 太多的 if 语句
- rabbitmq - 陈旧的 rabbitmq 数据队列文件占用了磁盘
- python - scapy 在 windows/parrotsec (pycharm) 上不起作用
- node.js - Ethereiun Solidity Contract - 挂钩问题之前
- c++ - C ++中无序集的内部工作是什么?它使用什么算法?
- c# - 如何使用多个列表框组合格式化代码
- wso2 - 使用发送调解器调用端点后,我收到以下错误响应
- html - 如何使用 tinymce 发布自定义 html 标签
- reactjs - 将 React 函数组件转换为 React 类组件
- java - 创建了新实例,但找不到符号错误仍然存在