Skip to content

Commit 03cfef0

Browse files
fdamhautLucasLefevre
authored andcommitted
[IMP] jest: add toBeCloseTo to object Matcher
Part-of: #7376 Signed-off-by: Lucas Lefèvre (lul) <[email protected]>
1 parent 1347d46 commit 03cfef0

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

tests/setup/jest_extend.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ declare global {
4545
interface Expect {
4646
toBeBetween(lower: number, upper: number): ExpectResult;
4747
toBeSameColorAs(expected: string, tolerance?: number): ExpectResult;
48+
toBeCloseTo(expected: number, closeDigit?: number): ExpectResult;
4849
}
4950
}
5051
}
@@ -190,6 +191,20 @@ CancelledReasons: ${this.utils.printReceived(dispatchResult.reasons)}
190191
}
191192
return { pass: true, message: () => "" };
192193
},
194+
toBeCloseTo(received: number, expected: number, numDigits?: number) {
195+
numDigits = numDigits ?? -2;
196+
const pass = Math.abs(expected - received) < 10 ** numDigits / 2;
197+
if (pass) {
198+
return { pass: true, message: () => "" };
199+
}
200+
return {
201+
pass: false,
202+
message: () =>
203+
`Expected ${received} to be close to ${expected} with a tolerance of ${
204+
10 ** numDigits / 2
205+
}`,
206+
};
207+
},
193208
toBeSameColorAs(received: string, expected: string, tolerance: number = 0) {
194209
let pass = false;
195210
if (received.startsWith("light-dark") || expected.startsWith("light-dark")) {

0 commit comments

Comments
 (0)