template-literals.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 \${"bar"}`).toBe('foo ${"bar"}');
  11. });
  12. test("literals in expressions", () => {
  13. expect(`foo ${undefined}`).toBe("foo undefined");
  14. expect(`foo ${null}`).toBe("foo null");
  15. expect(`foo ${5}`).toBe("foo 5");
  16. expect(`foo ${true}`).toBe("foo true");
  17. expect(`foo ${"bar"}`).toBe("foo bar");
  18. });
  19. test("objects in expressions", () => {
  20. expect(`foo ${{}}`).toBe("foo [object Object]");
  21. expect(`foo ${{ bar: { baz: "qux" } }}`).toBe("foo [object Object]");
  22. });
  23. test("expressions at beginning of template literal", () => {
  24. expect(`${"foo"} bar baz`).toBe("foo bar baz");
  25. expect(`${"foo bar baz"}`).toBe("foo bar baz");
  26. });
  27. test("multiple template literals", () => {
  28. expect(`foo ${"bar"} ${"baz"}`).toBe("foo bar baz");
  29. });
  30. test("variables in expressions", () => {
  31. let a = 27;
  32. expect(`${a}`).toBe("27");
  33. expect(`foo ${a}`).toBe("foo 27");
  34. expect(`foo ${a ? "bar" : "baz"}`).toBe("foo bar");
  35. expect(`foo ${(() => a)()}`).toBe("foo 27");
  36. });
  37. test("template literals in expressions", () => {
  38. expect(`foo ${`bar`}`).toBe("foo bar");
  39. expect(`${`${`${`${"foo"}`} bar`}`}`).toBe("foo bar");
  40. });
  41. test("newline literals (not characters)", () => {
  42. expect(
  43. `foo
  44. bar`
  45. ).toBe("foo\n bar");
  46. });
  47. test("line continuation in literals (not characters)", () => {
  48. expect(
  49. `foo\
  50. bar`
  51. ).toBe("foo bar");
  52. });
  53. test("reference error from expressions", () => {
  54. expect(() => `${b}`).toThrowWithMessage(ReferenceError, "'b' is not defined");
  55. });