I am having trouble generating an expired JWT token for testing purposes and need some guidance on how to approach it.
How do you handle expiration times in unit tests?
This is what I have attempted so far :
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')
})
Console error :
● 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)