Skip to content

Conversation

@sundaray
Copy link
Contributor

@sundaray sundaray commented Jan 8, 2026

The issue

Inside session.spec.ts, in the following 7 test cases:

  1. should attempt to refresh the session when the access token is invalid
  2. should delete the cookie when refreshing fails
  3. should delete the cookie and redirect when refreshing fails
  4. should call onSessionRefreshSuccess when refresh succeeds
  5. should call onSessionRefreshError when refresh fails
  6. should set JWT cookie after successful session refresh
  7. should delete JWT cookie when session refresh fails

We have this code:

mockSession.accessToken = await generateTestToken({}, true); 

(jwtVerify as jest.Mock).mockImplementation(() => {
    throw new Error('Invalid token');
});

The issue is that whether the generated test token is valid or not doesn’t have any impact on the outcome of the test. For example, I can create a valid token by passing false as the second argument to generateTestToken() and the test would still pass. This is because the jwtVerify() mock, instead of checking the expiration of the test token, is hard-coded to throw an “Invalid token” error.

The fix

Now, inside the jwtVerify() mock implementation, I check for the expiry of the test token and throw an "Invalid token" error ONLY when the token is expired.

mockSession.accessToken = await generateTestToken({}, true);

// Advance time by 1 second so exp < now
jest.advanceTimersByTime(1000);

(jwtVerify as jest.Mock).mockImplementation(async (token) => {
    const decodedJwt = decodeJwt(token);

    const now = Math.floor(Date.now() / 1000);

     if (decodedJwt.exp && decodedJwt.exp < now) {
         throw new Error('Invalid token');
     }

    return { payload: decodedJwt };
});

Note: Since the test token is generated with immediate expiry (0 seconds) via the true flag, I advance the fake timer by 1 second so the expiration check fails as expected.

@sundaray sundaray requested a review from a team as a code owner January 8, 2026 10:42
@sundaray sundaray requested a review from stacurry January 8, 2026 10:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant