-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create custom asymmetric matcher to test if a value is between two nu…
…mbers
- Loading branch information
1 parent
3e48711
commit 098ab73
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import { expect } from '@jest/globals'; | ||
|
||
const TIMED_OUT = Symbol(); | ||
|
||
function timeout(ms: number) { | ||
return new Promise<typeof TIMED_OUT>((resolve) => { | ||
setTimeout(() => resolve(TIMED_OUT), ms); | ||
}); | ||
} | ||
|
||
expect.extend({ | ||
async toSettle(testPromise: Promise<unknown>, ms: number) { | ||
const promise = await Promise.race([testPromise, timeout(ms)]); | ||
const isExpectedResult = promise !== TIMED_OUT; | ||
|
||
if (isExpectedResult) { | ||
return { | ||
message: () => `Expected promise not to settle`, | ||
pass: true, | ||
}; | ||
} | ||
|
||
return { | ||
message: () => `Expected promise to settle, but timed out after ${ms}ms`, | ||
pass: false, | ||
}; | ||
}, | ||
numberBetween(received: number, argumentOne: number, argumentTwo: number) { | ||
if (argumentOne > argumentTwo) { | ||
// Switch values | ||
[argumentOne, argumentTwo] = [argumentTwo, argumentOne]; | ||
} | ||
|
||
const pass = received >= argumentOne && received <= argumentTwo; | ||
|
||
return { | ||
pass, | ||
message: pass | ||
? () => `expected ${received} not to be between ${argumentOne} and ${argumentTwo}` | ||
: () => `expected ${received} to be between ${argumentOne} and ${argumentTwo}`, | ||
}; | ||
}, | ||
}); |