1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-25 06:27:45 +00:00

LibJS: Implement Iterator.prototype.forEach

This commit is contained in:
Timothy Flynn 2023-06-25 13:58:45 -04:00 committed by Andreas Kling
parent 35380b2aef
commit 134bb44ca0
3 changed files with 139 additions and 0 deletions

View file

@ -0,0 +1,94 @@
describe("errors", () => {
test("called with non-callable object", () => {
expect(() => {
Iterator.prototype.forEach(Symbol.hasInstance);
}).toThrowWithMessage(TypeError, "fn is not a function");
});
test("iterator's next method throws", () => {
function TestError() {}
class TestIterator extends Iterator {
next() {
throw new TestError();
}
}
expect(() => {
new TestIterator().forEach(() => 0);
}).toThrow(TestError);
});
test("value returned by iterator's next method throws", () => {
function TestError() {}
class TestIterator extends Iterator {
next() {
return {
done: false,
get value() {
throw new TestError();
},
};
}
}
expect(() => {
new TestIterator().forEach(() => 0);
}).toThrow(TestError);
});
test("for-each function throws", () => {
function TestError() {}
class TestIterator extends Iterator {
next() {
return {
done: false,
value: 1,
};
}
}
expect(() => {
new TestIterator().forEach(() => {
throw new TestError();
});
}).toThrow(TestError);
});
});
describe("normal behavior", () => {
test("length is 1", () => {
expect(Iterator.prototype.forEach).toHaveLength(1);
});
test("for-each function sees every value", () => {
function* generator() {
yield "a";
yield "b";
}
let count = 0;
generator().forEach((value, index) => {
++count;
switch (index) {
case 0:
expect(value).toBe("a");
break;
case 1:
expect(value).toBe("b");
break;
default:
expect().fail(`Unexpected reducer invocation: value=${value} index=${index}`);
break;
}
return value;
}, "");
expect(count).toBe(2);
});
});