setupTests.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // vitest.setup.ts
  2. import "vitest-canvas-mock";
  3. import "@testing-library/jest-dom";
  4. import fs from "fs";
  5. import { vi } from "vitest";
  6. import polyfill from "./packages/excalidraw/polyfill";
  7. import { testPolyfills } from "./packages/excalidraw/tests/helpers/polyfills";
  8. Object.assign(globalThis, testPolyfills);
  9. require("fake-indexeddb/auto");
  10. polyfill();
  11. Object.defineProperty(window, "matchMedia", {
  12. writable: true,
  13. value: vi.fn().mockImplementation((query) => ({
  14. matches: false,
  15. media: query,
  16. onchange: null,
  17. addListener: vi.fn(), // deprecated
  18. removeListener: vi.fn(), // deprecated
  19. addEventListener: vi.fn(),
  20. removeEventListener: vi.fn(),
  21. dispatchEvent: vi.fn(),
  22. })),
  23. });
  24. Object.defineProperty(window, "FontFace", {
  25. enumerable: true,
  26. value: class {
  27. private family: string;
  28. private source: string;
  29. private descriptors: any;
  30. private status: string;
  31. constructor(family, source, descriptors) {
  32. this.family = family;
  33. this.source = source;
  34. this.descriptors = descriptors;
  35. this.status = "unloaded";
  36. }
  37. load() {
  38. this.status = "loaded";
  39. }
  40. },
  41. });
  42. Object.defineProperty(document, "fonts", {
  43. value: {
  44. load: vi.fn().mockResolvedValue([]),
  45. check: vi.fn().mockResolvedValue(true),
  46. has: vi.fn().mockResolvedValue(true),
  47. add: vi.fn(),
  48. },
  49. });
  50. Object.defineProperty(window, "EXCALIDRAW_ASSET_PATH", {
  51. value: `file://${__dirname}/`,
  52. });
  53. vi.mock(
  54. "./packages/excalidraw/fonts/ExcalidrawFont",
  55. async (importOriginal) => {
  56. const mod = await importOriginal<
  57. typeof import("./packages/excalidraw/fonts/ExcalidrawFont")
  58. >();
  59. const ExcalidrawFontImpl = mod.ExcalidrawFont;
  60. return {
  61. ...mod,
  62. ExcalidrawFont: class extends ExcalidrawFontImpl {
  63. public async getContent(): Promise<string> {
  64. const url = this.urls[0];
  65. if (url.protocol !== "file:") {
  66. return super.getContent();
  67. }
  68. // read local assets directly, without running a server
  69. const content = await fs.promises.readFile(url);
  70. return `data:font/woff2;base64,${content.toString("base64")}`;
  71. }
  72. },
  73. };
  74. },
  75. );
  76. vi.mock("nanoid", () => {
  77. return {
  78. nanoid: vi.fn(() => "test-id"),
  79. };
  80. });
  81. // ReactDOM is located inside index.tsx file
  82. // as a result, we need a place for it to render into
  83. const element = document.createElement("div");
  84. element.id = "root";
  85. document.body.appendChild(element);