for-of-basic.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. describe("correct behavior", () => {
  2. test("iterate through array", () => {
  3. const a = [];
  4. for (const num of [1, 2, 3]) {
  5. a.push(num);
  6. }
  7. expect(a).toEqual([1, 2, 3]);
  8. });
  9. test("iterate through string", () => {
  10. const a = [];
  11. for (const char of "hello") {
  12. a.push(char);
  13. }
  14. expect(a).toEqual(["h", "e", "l", "l", "o"]);
  15. });
  16. test("iterate through string object", () => {
  17. const a = [];
  18. for (const char of new String("hello")) {
  19. a.push(char);
  20. }
  21. expect(a).toEqual(["h", "e", "l", "l", "o"]);
  22. });
  23. test("use already-declared variable", () => {
  24. var char;
  25. for (char of "abc");
  26. expect(char).toBe("c");
  27. });
  28. test("respects custom Symbol.iterator method", () => {
  29. const o = {
  30. [Symbol.iterator]() {
  31. return {
  32. i: 0,
  33. next() {
  34. if (this.i++ == 3) {
  35. return { done: true };
  36. }
  37. return { value: this.i, done: false };
  38. },
  39. };
  40. },
  41. };
  42. const a = [];
  43. for (const k of o) {
  44. a.push(k);
  45. }
  46. expect(a).toEqual([1, 2, 3]);
  47. });
  48. test("loops through custom iterator if there is an exception thrown part way through", () => {
  49. // This tests against the way custom iterators used to be implemented, where the values
  50. // were all collected at once before the for-of body was executed, instead of getting
  51. // the values one at a time
  52. const o = {
  53. [Symbol.iterator]() {
  54. return {
  55. i: 0,
  56. next() {
  57. if (this.i++ === 3) {
  58. throw new Error();
  59. }
  60. return { value: this.i };
  61. },
  62. };
  63. },
  64. };
  65. const a = [];
  66. try {
  67. for (let k of o) {
  68. a.push(k);
  69. }
  70. expect().fail();
  71. } catch (e) {
  72. expect(a).toEqual([1, 2, 3]);
  73. }
  74. });
  75. });
  76. describe("errors", () => {
  77. test("right hand side is a primitive", () => {
  78. expect(() => {
  79. for (const _ of 123) {
  80. }
  81. }).toThrowWithMessage(TypeError, "123 is not iterable");
  82. });
  83. test("right hand side is an object", () => {
  84. expect(() => {
  85. for (const _ of { foo: 1, bar: 2 }) {
  86. }
  87. }).toThrowWithMessage(TypeError, "[object Object] is not iterable");
  88. });
  89. });
  90. test("allow binding patterns", () => {
  91. expect(`for (let [a, b] of foo) {}`).toEval();
  92. });