template-literals.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. test("plain literals with expression-like characters", () => {
  2. expect(`foo`).toBe("foo");
  3. expect(`foo{`).toBe("foo{");
  4. expect(`foo}`).toBe("foo}");
  5. expect(`foo$`).toBe("foo$");
  6. });
  7. test("plain literals with escaped special characters", () => {
  8. expect(`foo\``).toBe("foo`");
  9. expect(`foo\\`).toBe("foo\\");
  10. expect(`foo\\\``).toBe("foo\\`");
  11. expect(`foo\\\\`).toBe("foo\\\\");
  12. expect(`foo\$`).toBe("foo$");
  13. expect(`foo \${"bar"}`).toBe('foo ${"bar"}');
  14. });
  15. test("literals in expressions", () => {
  16. expect(`foo ${undefined}`).toBe("foo undefined");
  17. expect(`foo ${null}`).toBe("foo null");
  18. expect(`foo ${5}`).toBe("foo 5");
  19. expect(`foo ${true}`).toBe("foo true");
  20. expect(`foo ${"bar"}`).toBe("foo bar");
  21. });
  22. test("objects in expressions", () => {
  23. expect(`foo ${{}}`).toBe("foo [object Object]");
  24. expect(`foo ${{ bar: { baz: "qux" } }}`).toBe("foo [object Object]");
  25. });
  26. test("expressions at beginning of template literal", () => {
  27. expect(`${"foo"} bar baz`).toBe("foo bar baz");
  28. expect(`${"foo bar baz"}`).toBe("foo bar baz");
  29. });
  30. test("multiple template literals", () => {
  31. expect(`foo ${"bar"} ${"baz"}`).toBe("foo bar baz");
  32. });
  33. test("variables in expressions", () => {
  34. let a = 27;
  35. expect(`${a}`).toBe("27");
  36. expect(`foo ${a}`).toBe("foo 27");
  37. expect(`foo ${a ? "bar" : "baz"}`).toBe("foo bar");
  38. expect(`foo ${(() => a)()}`).toBe("foo 27");
  39. });
  40. test("template literals in expressions", () => {
  41. expect(`foo ${`bar`}`).toBe("foo bar");
  42. expect(`${`${`${`${"foo"}`} bar`}`}`).toBe("foo bar");
  43. });
  44. test("newline literals (not characters)", () => {
  45. expect(
  46. `foo
  47. bar`
  48. ).toBe("foo\n bar");
  49. });
  50. test("line continuation in literals (not characters)", () => {
  51. expect(
  52. `foo\
  53. bar`
  54. ).toBe("foo bar");
  55. });
  56. test("reference error from expressions", () => {
  57. expect(() => `${b}`).toThrowWithMessage(ReferenceError, "'b' is not defined");
  58. });
  59. test("invalid escapes should give syntax error", () => {
  60. expect("`\\u`").not.toEval();
  61. expect("`\\01`").not.toEval();
  62. expect("`\\u{10FFFFF}`").not.toEval();
  63. });