optional-chaining.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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. // FIXME: This should pass.
  14. // expect("(new Foo)?.bar").toEval();
  15. });
  16. test("evaluate optional-chaining", () => {
  17. for (let nullishObject of [null, undefined]) {
  18. expect((() => nullishObject?.b)()).toBeUndefined();
  19. }
  20. expect(
  21. (() => {
  22. let a = {};
  23. return a?.foo?.bar?.baz;
  24. })()
  25. ).toBeUndefined();
  26. expect(
  27. (() => {
  28. let a = { foo: { bar: () => 42 } };
  29. return `${a?.foo?.bar?.()}-${a?.foo?.baz?.()}`;
  30. })()
  31. ).toBe("42-undefined");
  32. expect(() => {
  33. let a = { foo: { bar: () => 42 } };
  34. return a.foo?.baz.nonExistentProperty;
  35. }).toThrow();
  36. });