Profectus/tests/utils.ts

38 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-02-07 14:31:09 +00:00
import Decimal, { DecimalSource, format } from "util/bignum";
2023-05-04 17:40:03 +00:00
import { expect } from "vitest";
2023-02-07 14:31:09 +00:00
interface CustomMatchers<R = unknown> {
2023-04-02 04:42:12 +00:00
compare_tolerance(expected: DecimalSource, tolerance?: number): R;
2023-02-07 14:31:09 +00:00
}
declare module "vitest" {
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface Assertion extends CustomMatchers {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface AsymmetricMatchersContaining extends CustomMatchers {}
2023-02-07 14:31:09 +00:00
}
expect.extend({
2023-04-02 04:42:12 +00:00
compare_tolerance(received: DecimalSource, expected: DecimalSource, tolerance?: number) {
2023-02-07 14:31:09 +00:00
const { isNot } = this;
let pass = false;
if (!Decimal.isFinite(expected)) {
pass = !Decimal.isFinite(received);
} else if (Decimal.isNaN(expected)) {
pass = Decimal.isNaN(received);
} else {
2023-04-02 04:42:12 +00:00
pass = Decimal.eq_tolerance(received, expected, tolerance);
2023-02-07 14:31:09 +00:00
}
return {
// do not alter your "pass" based on isNot. Vitest does it for you
pass,
message: () =>
`Expected ${received} to${
(isNot as boolean) ? " not" : ""
} be close to ${expected}`,
expected: format(expected),
actual: format(received)
};
}
});