Unit testing of an expired JWT token fails due to the incorrect setting of the "options.expiresIn" parameter, as the payload already contains an "exp" property

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)

Answer №1

My solution involved correctly handling the expired time in the following code:

it('should generate a new token if it has expired', async () => {
  const userId = 1
  const userInfo = { sub: userId }
  const initialToken = jwtService.sign(userInfo, { expiresIn: 0 })
  const decodedToken = jwtService.decode(initialToken)
  console.log(decodedToken)
  expect(jwtService.verify(initialToken)).toThrowError('TokenExpiredError')
})

https://github.com/nestjs/jwt/issues/1#issuecomment-591281569

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the significance of syntax in sample code (typescript, react)?

const sampleFunction: (inputString: string) => string = inputString => { return inputString.split(""); } I'm a bit confused about the code below and would appreciate some clarification. I understand that only "string" as a type is accepted, b ...

Expanding material UI theme choices through module augmentation is currently ineffective with TypeText

For those experiencing the issue, a codesandbox has been provided for convenience. Click here to access the codesandbox. Curiously, the TypeText feature is not functioning properly while the SimplePaletteColorOptions is working as expected. Despite being ...

Struggling with object type casting in Typescript

Having issues with casting objects from an HTTP API response to Typescript. I am trying to cast the json data to a Typescript object using the "as" keyword or <Type >, but it's not working as expected. r.forEach(entry => { entry.creatio ...

What is the best way to strip out a changing segment of text from a string?

let: string str = "a=<random text> a=pattern:<random text (may be fixed length)> a=<random text>"; In the given string above, let's assume that a= and pattern are constants. It is possible that there may or may not be a ...

When using tsdx with React, null values can prevent proper usage of hooks

Recently, I attempted to develop a React TypeScript component using tsdx for compilation and encountered a roadblock while debugging. The package appears to be successfully published and installed without any errors. However, when trying to use it, I consi ...

What is the best way to switch to a different screen in a React Native application?

I've recently dived into the world of React Native and embarked on a new project. The initial screen that greets users upon launching the app is the "welcome screen," complete with a prominent 'continue' button. Ideally, clicking this button ...

Converting a "String" value to a specific "Type" in Angular 2 using TypeScript

This is my current object, Home points to the import statement for Home component. import { Home } from '../home/home'; arr = [ { name: "Home", root: Home, icon: "calc" } ]; This is what I want to achieve: import { Home } from & ...

An uncaught security error occurred when attempting to execute the 'pushState' function on the 'History' object

Here are the routes in my application: const routes:Routes =[ {path:'', component:WelcomeComponent}, {path:'profile', component: ProfileComponent}, {path:'addcourse', component: AddcourseComponent}, {path:'course ...

Is it possible to convert a DynamoDB AttributeMap type into an interface?

Assume I define a TypeScript interface like this: interface IPerson { id: string, name: string } If I perform a table scan on the 'persons' table in DynamoDB, my goal is to achieve the following: const client = new AWS.DynamoDB.Documen ...

Angular 2 decorators grant access to private class members

Take a look at this piece of code: export class Character { constructor(private id: number, private name: string) {} } @Component({ selector: 'my-app', template: '<h1>{{title}}</h1><h2>{{character.name}} detai ...

Enroll a nearby variable "Data" to an Observable belonging to a different Component within an Angular application

Looking to update the HTML view using *ngIf, depending on a local variable that should change based on an observable variable from a shared service. HTML <div class="login-container" *ngIf="!isAuthenticated"> TypeScript code for the same componen ...

What is the procedure for linking the value (<p>John</p>) to the mat form field input so that it displays as "John"?

Can I apply innerHTML to the value received from the backend and connect it to the matInput? Is this a viable option? ...

Can you explain the variances between the two Pick<T,K> util type implementations?

Here is a link I am exploring: https://github.com/type-challenges/type-challenges/blob/master/questions/4-easy-pick/README.md I am struggling to grasp the distinction between these two code snippets: type MyPick<T, K> = T extends {} ? K extends keyo ...

Sending an object between two components without a direct parent-child connection

Hello, I have a question similar to the one asked on Stack Overflow regarding passing a value from one Angular 2 component to another without a parent-child relationship. In my scenario, Component1 subscribes to a service that makes a GET request to the ...

Errors with the email composer in Ionic 3 displaying "plugin_not_installed" issue

Currently utilizing this feature within my Ionic 3 application. The plugin has been successfully installed, and the cordova-plugin-email-composer folder is present in the plugins directory. Despite multiple attempts of uninstalling and reinstalling, an err ...

Using dynamic imports to enhance code by adding the `.at()` function can lead to errors in the process

Below is the content of my .tsconfig configuration file: { "compilerOptions": { "target": "es6", "baseUrl": "./src", "lib": ["dom", "dom.iterable", "esnext&q ...

Passing data to a child component using Context in React is not working

I have a parent component where I am storing data in an array of objects and then passing it to another component through Context. Here is how my parent component looks: export type HistoryData = { input: string; date: string; ...

Using Angular 2 to round a calculated number within HTML

In the HTML code, there is a calculated number associated with Component1. Component1 serves as a tab page within a Bootstrap tab panel. Below is the HTML code with the tab panel: <div id="minimal-tabs" style="padding:75px;padding-top:60 ...

Error: The body is not usable - POST action from NextJS server

In my project with NextJS v14.1.0, I encountered an issue while using server action in a client component. The error message is showing correctly, but I also receive a TypeError stating that the body is unusable. src/app/auth/account-verification/page.tsx ...

Managing two subscriptions based on conditions in Angular

I'm currently working on a component that includes the following code snippet: this.service().subscribe((result) => { this.service2(result).subscribe((result2) => //other code }} As I strive to follow best practices in Angular development, I&ap ...