optional-chaining.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. test("parse optional-chaining", () => {
  2. expect(`a?.b`).toEval();
  3. expect(`a?.4:.5`).toEval();
  4. expect(`a?.[b]`).toEval();
  5. expect(`a?.b[b]`).toEval();
  6. expect(`a?.b(c)`).toEval();
  7. expect(`a?.b?.(c, d)`).toEval();
  8. expect(`a?.b?.()`).toEval();
  9. expect("a?.b``").not.toEval();
  10. expect("a?.b?.``").not.toEval();
  11. expect("new Foo?.bar").not.toEval();
  12. expect("new (Foo?.bar)").toEval();
  13. expect("(new Foo)?.bar").toEval();
  14. });
  15. test("evaluate optional-chaining", () => {
  16. for (let nullishObject of [null, undefined]) {
  17. expect((() => nullishObject?.b)()).toBeUndefined();
  18. }
  19. expect(
  20. (() => {
  21. let a = {};
  22. return a?.foo?.bar?.baz;
  23. })()
  24. ).toBeUndefined();
  25. expect(
  26. (() => {
  27. let a = { foo: { bar: () => 42 } };
  28. return `${a?.foo?.bar?.()}-${a?.foo?.baz?.()}`;
  29. })()
  30. ).toBe("42-undefined");
  31. expect(() => {
  32. let a = { foo: { bar: () => 42 } };
  33. return a.foo?.baz.nonExistentProperty;
  34. }).toThrow();
  35. });