首页 > 解决方案 > 单元测试过期的 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)

标签: typescriptunit-testingjestjsjwt

解决方案


我通过正确传递过期时间来解决它:

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


推荐阅读