Created
August 8, 2019 22:32
-
-
Save kevinold/d8c4aa9c3c0266a145a0e6450e361aeb to your computer and use it in GitHub Desktop.
Test that a JWT is expired or expires within a certain window using Sinon's Fake Timers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import expect from "expect"; | |
import sinon from "sinon"; | |
// Inline version of function to be tested | |
const expiredOrExpiresWithin = (decodedJwt, seconds) => | |
Date.now() >= (decodedJwt.exp + (-Math.abs(seconds) || 0)) * 1000; | |
describe("jwtUtils", () => { | |
describe("expiredOrExpiresWithin", () => { | |
let clock; | |
let decodedJwt; | |
beforeEach(() => { | |
clock = sinon.useFakeTimers(new Date(2018, 7, 29).getTime()); // sets date to Aug 29, 2018 at 00:00 UTC | |
decodedJwt = { | |
data: "foobar", | |
iat: 1535566191, | |
exp: 1535566197, // Wed Aug 29 2018 18:09:57 GMT+0000 (UTC) | |
}; | |
/* const d = new Date(0); */ | |
/* d.setUTCSeconds(decodedJwt.exp); */ | |
/* console.log("JWT Date", d); */ | |
}); | |
afterEach(() => { | |
clock.restore(); | |
}); | |
it("should be expired if jwt exp is in the past", () => { | |
clock.tick(60 * 60 * 19 * 1000); // move the fake time ahead to 19:00:00 | |
/* console.log("Now Date", new Date()); */ | |
expect(expiredOrExpiresWithin(decodedJwt, 0)).toBe(true); | |
}); | |
it("should NOT be expired if jwt exp is in the future", () => { | |
/* console.log("Now Date", new Date()); */ | |
expect(expiredOrExpiresWithin(decodedJwt, 0)).toBe(false); | |
}); | |
it("should be expired if jwt exp is in the future out of tolerance (1 minute - dev)", () => { | |
clock.tick(60 * 60 * 18.16 * 1000); // move the fake time ahead to 18:09:36 | |
/* console.log("Now Date", new Date()); */ | |
expect(expiredOrExpiresWithin(decodedJwt, 60)).toBe(true); | |
}); | |
it("should NOT be expired if jwt exp is in the future greater than tolerance", () => { | |
/* console.log("Now Date", new Date()); */ | |
expect(expiredOrExpiresWithin(decodedJwt, 60)).toBe(false); | |
}); | |
it("should be expired if jwt exp is in the future out of tolerance (1 hour - production)", () => { | |
clock.tick(60 * 60 * 18.16 * 1000); // move the fake time ahead to 18:09:36 | |
/* console.log("Now Date", new Date()); */ | |
expect(expiredOrExpiresWithin(decodedJwt, 60 * 60)).toBe(true); | |
}); | |
}); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment