Planar-Pioneers/tests/utils.ts

62 lines
2 KiB
TypeScript
Raw Normal View History

2023-02-07 14:31:09 +00:00
import Decimal, { DecimalSource, format } from "util/bignum";
2023-05-17 05:37:33 +00:00
import { Mock, expect, vi } 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-05-17 05:37:33 +00:00
toLogError(): R;
2023-02-07 14:31:09 +00:00
}
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Vi {
// 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 {}
}
}
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)
};
2023-05-17 05:37:33 +00:00
},
toLogError(received: () => unknown) {
const { isNot } = this;
console.error = vi.fn();
received();
const calls = (
console.error as unknown as Mock<
Parameters<typeof console.error>,
ReturnType<typeof console.error>
>
).mock.calls.length;
const pass = calls >= 1;
vi.restoreAllMocks();
return {
pass,
message: () =>
`Expected ${received} to ${(isNot as boolean) ? " not" : ""} log an error`,
expected: "1+",
actual: calls
};
2023-02-07 14:31:09 +00:00
}
});