typescript - 单元测试过期的 JWT 令牌错误的“options.expiresIn”选项有效负载已经具有“exp”属性
问题描述
我正在尝试生成一个已经过期的 JWT 令牌用于测试目的,但我无法找到正确的方法。
您如何管理单元测试中的过期时间?
到目前为止,这是我的尝试:
it('should return a new token if expired', async () => {
const candidateId = 1
const oneHourLessFromNow = Math.floor(Date.now() / 1000) - 3600
const payload = { sub: candidateId, exp: oneHourLessFromNow }
const initialToken = jwtService.sign(payload)
const decodedInitialToken = jwtService.decode(initialToken)
console.log(decodedInitialToken)
expect(jwtService.verify(initialToken)).toThrowError('TokenExpiredError')
})
控制台错误:
● AuthService › refresh › should return a new token if expired
Bad "options.expiresIn" option the payload already has an "exp" property.
113 | const oneHourLessFromNow = Math.floor(Date.now() / 1000) - 3600
114 | const payload = { sub: candidateId, exp: oneHourLessFromNow }
> 115 | const initialToken = jwtService.sign(payload)
| ^
116 | const decodedInitialToken = jwtService.decode(initialToken)
117 | console.log(decodedInitialToken)
118 | expect(jwtService.verify(initialToken)).toThrowError('TokenExpiredError')
at Object.module.exports [as sign] (../node_modules/jsonwebtoken/sign.js:133:20)
at JwtService.sign (../node_modules/@nestjs/jwt/dist/jwt.service.js:27:20)
at Object.<anonymous> (auth/auth.service.spec.ts:115:39)
console.error
undefined
44 | return this.createToken(candidateId)
45 | } catch (e) {
> 46 | console.error(e)
| ^
47 | throw new HttpException(
48 | ResponseMessage.INVALID_CODE,
49 | HttpStatus.FORBIDDEN
at AuthService.verifySmsCode (auth/auth.service.ts:46:15)
console.log
{ sub: 1, iat: 1602496713, exp: 1602500313 }
at AuthService.refresh (auth/auth.service.ts:59:13)
解决方案
我通过正确传递过期时间来解决它:
it('should return a new token if expired', async () => {
const candidateId = 1
const payload = { sub: candidateId }
const initialToken = jwtService.sign(payload, { expiresIn: 0 })
const decodedInitialToken = jwtService.decode(initialToken)
console.log(decodedInitialToken)
expect(jwtService.verify(initialToken)).toThrowError('TokenExpiredError')
})
https://github.com/nestjs/jwt/issues/1#issuecomment-591281569
推荐阅读
- amazon-web-services - Terraform aws 安全组更改
- javascript - 如果 JSON 数据中存在数据,则输入 onchange 检查器
- protocol-buffers - 在 protobuf 流中复用/解复用不同的消息类型
- css - 为什么 symfony 形式的复选框看起来很奇怪?
- node.js - 当 fs.watch 检测到文件取消链接时获取 fs.stat
- javascript - Vuetify 文本字段在一行
- android - xamarin android 实时通知应用 uber 类似
- python - 是否有一些云解决方案可以在 Python 中训练模型并将结果导入 GBQ?
- azure - 全球可用的 Azure 应用架构/设计?
- java - 如果定义(非空)如何使用自定义处理器?