Skip to content

Commit

Permalink
Create custom asymmetric matcher to test if a value is between two nu…
Browse files Browse the repository at this point in the history
…mbers
  • Loading branch information
nibble-4bits committed Oct 15, 2023
1 parent 3e48711 commit 098ab73
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions __tests__/customMatchers.ts
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}`,
};
},
});

0 comments on commit 098ab73

Please sign in to comment.