1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 19:37:34 +00:00

LibJS: Implement Temporal.Duration.prototype.with()

This commit is contained in:
Linus Groh 2021-07-16 19:30:52 +01:00
parent 510f668ae3
commit 9aa1e4b885
7 changed files with 253 additions and 0 deletions

View file

@ -0,0 +1,87 @@
const DURATION_PROPERTIES = [
"years",
"months",
"weeks",
"days",
"hours",
"minutes",
"seconds",
"milliseconds",
"microseconds",
"nanoseconds",
];
describe("correct behavior", () => {
test("length is 1", () => {
expect(Temporal.Duration.prototype.with).toHaveLength(1);
});
test("basic functionality", () => {
const duration = new Temporal.Duration(1, 2, 3).with({ years: 4, foo: 5, weeks: 6 });
expect(duration.years).toBe(4);
expect(duration.months).toBe(2);
expect(duration.weeks).toBe(6);
});
test("each property is looked up from the object", () => {
for (const property of DURATION_PROPERTIES) {
const duration = new Temporal.Duration().with({ [property]: 1 });
expect(duration[property]).toBe(1);
}
});
test("each property is coerced to number", () => {
for (const property of DURATION_PROPERTIES) {
const duration = new Temporal.Duration().with({ [property]: "1" });
expect(duration[property]).toBe(1);
}
});
});
test("errors", () => {
test("this value must be a Temporal.Duration object", () => {
expect(() => {
Temporal.Duration.prototype.with.call("foo");
}).toThrowWithMessage(TypeError, "Not a Temporal.Duration");
});
test("argument is not an object", () => {
expect(() => {
new Temporal.Duration().with("foo");
}).toThrowWithMessage(TypeError, "foo is not an object");
expect(() => {
new Temporal.Duration().with(42);
}).toThrowWithMessage(TypeError, "42 is not an object");
});
test("argument is an invalid duration-like object", () => {
expect(() => {
new Temporal.Duration().with({});
}).toThrowWithMessage(TypeError, "Invalid duration-like object");
expect(() => {
new Temporal.Duration().with({ foo: 1, bar: 2 });
}).toThrowWithMessage(TypeError, "Invalid duration-like object");
});
test("error when coercing property to number", () => {
for (const property of DURATION_PROPERTIES) {
expect(() => {
new Temporal.Duration().with({
[property]: {
valueOf() {
throw new Error();
},
},
});
}).toThrow(Error);
}
});
test("invalid duration value", () => {
for (const property of DURATION_PROPERTIES) {
expect(() => {
new Temporal.Duration().with({ [property]: Infinity });
}).toThrowWithMessage(RangeError, "Invalid duration");
}
});
});