Created
January 13, 2021 03:20
-
-
Save alchemycs/b0140cd8e73b29e91cd01b40a9cb38bd to your computer and use it in GitHub Desktop.
Custom Jest Test For Clock Drift and Ranges
This file contains hidden or 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
// Define and declare a custom jest expectation so we can handle clock drift tolerances | |
declare global { | |
// eslint-disable-next-line @typescript-eslint/no-namespace | |
namespace jest { | |
interface Matchers<R> { | |
toBeWithinTolerance(center: number, tolerance: number): R; | |
} | |
} | |
} | |
expect.extend({ | |
toBeWithinTolerance(received: number, center: number, tolerance: number) { | |
const floor = center - tolerance; | |
const ceiling = center + tolerance; | |
const pass = received >= floor && received <= ceiling; | |
if (pass) { | |
return { | |
message: () => `expected ${received} not to be within tolerance range ${center}+/- ${tolerance} (${floor} - ${ceiling})`, | |
pass: true, | |
}; | |
} else { | |
return { | |
message: () => `expected ${received} to be within tolerance range ${center}+/- ${tolerance} (${floor} - ${ceiling})`, | |
pass: false, | |
}; | |
} | |
}, | |
}); | |
describe('DynamoTokenStore custom jest expectation .toBeWithinTolerance()', () => { | |
const center = 5; | |
const tolerance = 2; | |
const underflow = [0, 1, 2]; | |
const overflow = [8, 9, 10]; | |
const withinTolerance = [3, 4, 5, 6, 7]; | |
test.each(withinTolerance)(`should assert %p is within tolerance ${center}+/-${tolerance}`, (value) => { | |
expect(value).toBeWithinTolerance(center, tolerance); | |
}); | |
test.each(underflow)(`should assert underflow value %p is outside tolerance ${center}+/-${tolerance}`, (value) => { | |
expect(value).not.toBeWithinTolerance(center, tolerance); | |
}); | |
test.each(overflow)(`should assert overflow value %p is outside tolerance ${center}+/-${tolerance}`, (value) => { | |
expect(value).not.toBeWithinTolerance(center, tolerance); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment