diff --git a/Userland/Libraries/LibJS/Tests/test-common-tests.js b/Userland/Libraries/LibJS/Tests/test-common-tests.js index 1801bb078d..a239ddeaf7 100644 --- a/Userland/Libraries/LibJS/Tests/test-common-tests.js +++ b/Userland/Libraries/LibJS/Tests/test-common-tests.js @@ -36,6 +36,16 @@ test("toBeCloseTo", () => { expect(1).not.toBeCloseTo(1.00001); expect(1).toBeCloseTo(1.000001); + expect(1).not.toBeCloseTo(1.001, 3); + expect(1).toBeCloseTo(1.001, 2); + expect(1).not.toBeCloseTo(0, 0); + expect(6).toBeCloseTo(10, -1); + expect(125).toBeCloseTo(100, -2); + expect(3.14159).toBeCloseTo(3.14158, 4); + expect(() => { + expect(1).toBeCloseTo(1, "foo").toThrow(ExpectationError); + }).toThrow(ExpectationError); + [ ["foo", 1], [1, "foo"], diff --git a/Userland/Libraries/LibJS/Tests/test-common.js b/Userland/Libraries/LibJS/Tests/test-common.js index f7d7eb860f..25093ee516 100644 --- a/Userland/Libraries/LibJS/Tests/test-common.js +++ b/Userland/Libraries/LibJS/Tests/test-common.js @@ -86,8 +86,7 @@ class ExpectationError extends Error { }); } - // FIXME: Take a precision argument like jest's toBeCloseTo matcher - toBeCloseTo(value) { + toBeCloseTo(value, precision = 5) { this.__expect( typeof this.target === "number", () => `toBeCloseTo: expected target of type number, got ${typeof this.target}` @@ -96,9 +95,14 @@ class ExpectationError extends Error { typeof value === "number", () => `toBeCloseTo: expected argument of type number, got ${typeof value}` ); + this.__expect( + typeof precision === "number", + () => `toBeCloseTo: expected precision of type number, got ${typeof precision}` + ); + const epsilon = 10 ** -precision / 2; this.__doMatcher(() => { - this.__expect(Math.abs(this.target - value) < 0.000001); + this.__expect(Math.abs(this.target - value) < epsilon); }); }