function-new-target.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. test("basic functionality", () => {
  2. function foo() {
  3. return new.target;
  4. }
  5. expect(foo()).toBeUndefined();
  6. expect(new foo()).toEqual(foo);
  7. function bar() {
  8. const baz = () => new.target;
  9. return baz();
  10. }
  11. expect(bar()).toBeUndefined();
  12. expect(new bar()).toEqual(bar);
  13. class baz {
  14. constructor() {
  15. this.newTarget = new.target;
  16. }
  17. }
  18. expect(new baz().newTarget).toEqual(baz);
  19. });
  20. test("retrieving new.target from direct eval", () => {
  21. function foo() {
  22. return eval("new.target");
  23. }
  24. let result;
  25. expect(() => {
  26. result = foo();
  27. }).not.toThrowWithMessage(SyntaxError, "'new.target' not allowed outside of a function");
  28. expect(result).toBe(undefined);
  29. expect(() => {
  30. result = new foo();
  31. }).not.toThrowWithMessage(SyntaxError, "'new.target' not allowed outside of a function");
  32. expect(result).toBe(foo);
  33. });
  34. test("cannot retrieve new.target from indirect eval", () => {
  35. const indirect = eval;
  36. function foo() {
  37. return indirect("new.target");
  38. }
  39. expect(() => {
  40. foo();
  41. }).toThrowWithMessage(SyntaxError, "'new.target' not allowed outside of a function");
  42. expect(() => {
  43. new foo();
  44. }).toThrowWithMessage(SyntaxError, "'new.target' not allowed outside of a function");
  45. });
  46. test("syntax error outside of function", () => {
  47. expect("new.target").not.toEval();
  48. });