@jest/globals#beforeAll TypeScript Examples

The following examples show how to use @jest/globals#beforeAll. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GraphBuildSuccess.test.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
beforeAll(async () => {
  await TEST__buildGraphWithEntities(
    graphManagerState,
    TEST_DATA__m2mGraphEntities as Entity[],
  );
});
Example #2
Source File: MockDataUtil.test.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
beforeAll(async () => {
  await TEST__buildGraphWithEntities(
    editorStore.graphManagerState,
    TEST_DATA__completeGraphEntities as Entity[],
  );
});
Example #3
Source File: cts.spec.tsx    From slice-machine with Apache License 2.0 5 votes vote down vote up
beforeAll(() => server.listen());
Example #4
Source File: slices.spec.tsx    From slice-machine with Apache License 2.0 5 votes vote down vote up
beforeAll(() => server.listen());
Example #5
Source File: install-lib.test.ts    From slice-machine with Apache License 2.0 4 votes vote down vote up
describe("install-lib", () => {
  const fakeCWD = path.join(os.tmpdir(), "install-lib-test");
  jest.spyOn(process, "exit").mockReturnValue(void 0 as never);

  afterEach(() => {
    jest.clearAllMocks();
  });

  beforeAll(() => {
    if (fs.existsSync(fakeCWD)) {
      fs.rmSync(fakeCWD, { recursive: true, force: true });
    }
    fs.mkdirSync(fakeCWD, { recursive: true });
  });

  test("by default it downloads zip form the HEAD branch from github", async () => {
    const user = "prismicio";
    const project = "foo";
    const gitpath = path.posix.join(user, project);
    const branch = "HEAD";

    const Theme = new AdmZip();
    const themePath = path.join(__dirname, "__stubs__", "fake-project");

    Theme.addLocalFolder(themePath, `${project}-${branch}`);

    const zip = Theme.toBuffer();

    nock("https://codeload.github.com")
      .get(`/${gitpath}/zip/${branch}`)
      .reply(200, zip, {
        "Content-Type": "application/zip",
        "content-length": zip.length.toString(),
      });

    // quick fix, I would rather mock child_process.exec
    jest
      .spyOn(utils, "execCommand")
      .mockResolvedValue({ stderr: "", stdout: "" });

    stderr.start();
    stdout.start();
    const libs = await installLib(fakeCWD, gitpath);

    stderr.stop();
    stdout.stop();

    expect(
      fs.existsSync(path.join(fakeCWD, `${user}-${project}`, "meta.json"))
    ).toBeTruthy();

    expect(stderr.output).toContain(
      'Slice library "prismicio/foo" was installed successfully'
    );
    expect(libs).toContain(
      path.posix.join("~", `${user}-${project}`, "slices")
    );
  });

  test("it can take a branch as an argument", async () => {
    const user = "prismicio";
    const project = "baz";
    const gitpath = path.posix.join(user, project);
    const branch = "not-main-or-master";

    const Theme = new AdmZip();
    const themePath = path.join(__dirname, "__stubs__", "fake-project");

    Theme.addLocalFolder(themePath, `${project}-${branch}`);

    const zip = Theme.toBuffer();

    nock("https://codeload.github.com")
      .get(`/${gitpath}/zip/${branch}`)
      .reply(200, zip, {
        "Content-Type": "application/zip",
        "content-length": zip.length.toString(),
      });

    // quick fix, I would rather mock child_process.exec
    jest
      .spyOn(utils, "execCommand")
      .mockResolvedValue({ stderr: "", stdout: "" });

    stderr.start();
    stdout.start();
    const libs = await installLib(fakeCWD, gitpath, branch);
    stderr.stop();
    stderr.stop();

    expect(stderr.output).toContain(
      'Slice library "prismicio/baz" was installed successfully'
    );

    expect(
      fs.existsSync(path.join(fakeCWD, `${user}-${project}`, "meta.json"))
    ).toBeTruthy();

    expect(libs).toContain(
      path.posix.join("~", `${user}-${project}`, "slices")
    );
  });

  test("when given branch or project does not exist.", async () => {
    const user = "prismicio";
    const project = "batman";
    const gitpath = path.posix.join(user, project);
    const branch = "nope";

    nock("https://codeload.github.com")
      .get(`/${gitpath}/zip/${branch}`)
      .reply(404);

    // quick fix, I would rather mock child_process.exec
    jest
      .spyOn(utils, "execCommand")
      .mockResolvedValue({ stderr: "", stdout: "" });

    jest.spyOn(console, "error").mockImplementation(() => jest.fn());

    stderr.start();
    stdout.start();
    await installLib(fakeCWD, gitpath, branch);
    stderr.stop();
    stderr.stop();

    expect(console.error).toHaveBeenLastCalledWith(
      "Request failed with status code 404"
    );
  });
});
Example #6
Source File: cts.spec.tsx    From slice-machine with Apache License 2.0 4 votes vote down vote up
describe("Custom Type Builder", () => {
  const fakeTracker = jest.fn().mockImplementation(() => Promise.resolve());

  beforeAll(async () => {
    const div = document.createElement("div");
    div.setAttribute("id", "__next");
    document.body.appendChild(div);

    const fakeAnalytics = jest
      .spyOn(AnalyticsBrowser, "standalone")
      .mockResolvedValue({
        track: fakeTracker,
      } as any);

    await Tracker.get().initialize("foo", "repoName");
    expect(fakeAnalytics).toHaveBeenCalled();
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  beforeEach(async () => {
    mockRouter.setCurrentUrl("/");
  });

  test("should send a tracking event when the user adds a field", async () => {
    const customTypeId = "a-page";

    singletonRouter.push({
      pathname: "cts/[ct]",
      query: { ct: customTypeId },
    });

    const App = render(<CreateCustomTypeBuilder />, {
      preloadedState: {
        environment: {
          framework: "next",
          mockConfig: { _cts: { [customTypeId]: {} } },
        },
        availableCustomTypes: {
          [customTypeId]: {
            local: {
              id: customTypeId,
              label: customTypeId,
              repeatable: true,
              status: true,
              tabs: [
                {
                  key: "Main",
                  value: [],
                },
              ],
            },
          },
        },
        selectedCustomType: {
          model: {
            id: "a-page",
            label: "a-page",
            repeatable: true,
            status: true,
            tabs: [
              {
                key: "Main",
                value: [],
              },
            ],
          },
          initialModel: {
            id: "a-page",
            label: "a-page",
            repeatable: true,
            status: true,
            tabs: [
              {
                key: "Main",
                value: [],
              },
            ],
          },
          mockConfig: {},
          initialMockConfig: {},
        },
      },
    });

    const addButton = screen.getByTestId("empty-zone-add-new-field");
    fireEvent.click(addButton);

    const uid = screen.getByText("UID");
    fireEvent.click(uid);

    const saveFieldButton = screen.getByText("Add");

    await act(async () => {
      fireEvent.click(saveFieldButton);
    });

    expect(fakeTracker).toHaveBeenCalledWith(
      "SliceMachine Custom Type Field Added",
      { id: "uid", name: "a-page", type: "UID", zone: "static" },
      { context: { groupId: { Repository: "repoName" } } }
    );
  });

  test("should send a tracking event when the user adds a slice", async () => {
    const customTypeId = "a-page";

    singletonRouter.push({
      pathname: "cts/[ct]",
      query: { ct: customTypeId },
    });

    // duplicated state for library context :/

    const environment = {
      framework: "next",
      mockConfig: { _cts: { [customTypeId]: {} } },
    };

    const libraries = [
      {
        path: "./slices",
        isLocal: true,
        name: "slices",
        meta: {
          isNodeModule: false,
          isDownloaded: false,
          isManual: true,
        },
        components: [
          {
            from: "slices",
            href: "slices",
            pathToSlice: "./slices",
            fileName: "index",
            extension: "js",
            screenshotPaths: {},
            mock: [
              {
                variation: "default",
                name: "Default",
                slice_type: "test_slice",
                items: [],
                primary: {
                  title: [
                    {
                      type: "heading1",
                      text: "Cultivate granular e-services",
                      spans: [],
                    },
                  ],
                  description: [
                    {
                      type: "paragraph",
                      text: "Anim in commodo exercitation qui. Elit cillum officia mollit dolore. Commodo voluptate sit est proident ea proident dolor esse ad.",
                      spans: [],
                    },
                  ],
                },
              },
            ],
            model: {
              id: "test_slice",
              type: "SharedSlice",
              name: "TestSlice",
              description: "TestSlice",
              variations: [
                {
                  id: "default",
                  name: "Default",
                  docURL: "...",
                  version: "sktwi1xtmkfgx8626",
                  description: "TestSlice",
                  primary: [
                    {
                      key: "title",
                      value: {
                        type: "StructuredText",
                        config: {
                          single: "heading1",
                          label: "Title",
                          placeholder: "This is where it all begins...",
                        },
                      },
                    },
                    {
                      key: "description",
                      value: {
                        type: "StructuredText",
                        config: {
                          single: "paragraph",
                          label: "Description",
                          placeholder: "A nice description of your feature",
                        },
                      },
                    },
                  ],
                  items: [],
                  imageUrl:
                    "https://images.prismic.io/slice-machine/621a5ec4-0387-4bc5-9860-2dd46cbc07cd_default_ss.png?auto=compress,format",
                },
              ],
            },
            screenshotUrls: {},
            __status: "NEW_SLICE",
          },
        ],
      },
    ];

    const App = render(
      <LibrariesProvider
        env={environment}
        libraries={libraries}
        remoteSlices={[]}
      >
        <CreateCustomTypeBuilder />
      </LibrariesProvider>,
      {
        preloadedState: {
          environment,
          availableCustomTypes: {
            [customTypeId]: {
              local: {
                id: customTypeId,
                label: customTypeId,
                repeatable: true,
                status: true,
                tabs: [
                  {
                    key: "Main",
                    value: [],
                  },
                ],
              },
            },
          },
          selectedCustomType: {
            model: {
              id: "a-page",
              label: "a-page",
              repeatable: true,
              status: true,
              tabs: [
                {
                  key: "Main",
                  value: [],
                },
              ],
            },
            initialModel: {
              id: "a-page",
              label: "a-page",
              repeatable: true,
              status: true,
              tabs: [
                {
                  key: "Main",
                  value: [],
                },
              ],
            },
            mockConfig: {},
            initialMockConfig: {},
          },
          slices: {
            libraries,
            remoteSlices: [],
          },
        },
      }
    );

    const addButton = screen.getByTestId("empty-zone-add-a-new-slice");
    await act(async () => {
      fireEvent.click(addButton);
    });

    const slicesToSelect = screen.getAllByTestId("slicezone-modal-item");

    for (const elem of slicesToSelect) {
      await act(async () => {
        fireEvent.click(elem);
      });
    }

    const saveButton = screen.getByText("Save");

    await act(async () => {
      fireEvent.click(saveButton);
    });

    expect(fakeTracker).toHaveBeenCalledWith(
      "SliceMachine Slicezone Updated",
      { customTypeId },
      { context: { groupId: { Repository: "repoName" } } }
    );
  });

  test("it should send a tracking event when the user saves a custom-type", async () => {
    const customTypeId = "a-page";

    singletonRouter.push({
      pathname: "cts/[ct]",
      query: { ct: customTypeId },
    });

    const App = render(<CreateCustomTypeBuilder />, {
      preloadedState: {
        environment: {
          framework: "next",
          mockConfig: { _cts: { [customTypeId]: {} } },
        },
        availableCustomTypes: {
          [customTypeId]: {
            local: {
              id: customTypeId,
              label: customTypeId,
              repeatable: true,
              status: true,
              tabs: [
                {
                  key: "Main",
                  value: [],
                },
              ],
            },
          },
        },
        selectedCustomType: {
          model: {
            id: "a-page",
            label: "a-page",
            repeatable: true,
            status: true,
            tabs: [
              {
                key: "Main",
                value: [],
              },
            ],
          },
          initialModel: {
            id: "a-page",
            label: "a-page",
            repeatable: true,
            status: true,
            tabs: [
              {
                key: "Main",
                value: [],
              },
            ],
          },
          mockConfig: {},
          initialMockConfig: {},
        },
      },
    });

    const addButton = screen.getByTestId("empty-zone-add-new-field");
    fireEvent.click(addButton);

    const uid = screen.getByText("UID");
    fireEvent.click(uid);

    const saveFieldButton = screen.getByText("Add");

    await act(async () => {
      fireEvent.click(saveFieldButton);
    });

    expect(fakeTracker).toHaveBeenCalledWith(
      "SliceMachine Custom Type Field Added",
      { id: "uid", name: customTypeId, type: "UID", zone: "static" },
      { context: { groupId: { Repository: "repoName" } } }
    );

    const saveCustomType = screen.getByText("Save to File System");

    await act(async () => {
      fireEvent.click(saveCustomType);
    });

    await waitFor(() => {
      expect(fakeTracker).toHaveBeenLastCalledWith(
        "SliceMachine Custom Type Saved",
        { type: "repeatable", id: customTypeId, name: customTypeId },
        { context: { groupId: { Repository: "repoName" } } }
      );
    });
  });

  test("if saving fails a it should not send the save event", async () => {
    server.use(
      rest.post("/api/custom-types/save", (_, res, ctx) => {
        return res(ctx.status(500), ctx.json({}));
      })
    );
    const customTypeId = "a-page";

    singletonRouter.push({
      pathname: "cts/[ct]",
      query: { ct: customTypeId },
    });

    const App = render(<CreateCustomTypeBuilder />, {
      preloadedState: {
        environment: {
          framework: "next",
          mockConfig: { _cts: { [customTypeId]: {} } },
        },
        availableCustomTypes: {
          [customTypeId]: {
            local: {
              id: customTypeId,
              label: customTypeId,
              repeatable: true,
              status: true,
              tabs: [
                {
                  key: "Main",
                  value: [],
                },
              ],
            },
          },
        },
        selectedCustomType: {
          model: {
            id: "a-page",
            label: "a-page",
            repeatable: true,
            status: true,
            tabs: [
              {
                key: "Main",
                value: [],
              },
            ],
          },
          initialModel: {
            id: "a-page",
            label: "a-page",
            repeatable: true,
            status: true,
            tabs: [
              {
                key: "Main",
                value: [],
              },
            ],
          },
          mockConfig: {},
          initialMockConfig: {},
        },
      },
    });

    const addButton = screen.getByTestId("empty-zone-add-new-field");
    fireEvent.click(addButton);

    const uid = screen.getByText("UID");
    fireEvent.click(uid);

    const saveFieldButton = screen.getByText("Add");

    await act(async () => {
      fireEvent.click(saveFieldButton);
    });

    expect(fakeTracker).toHaveBeenCalledWith(
      "SliceMachine Custom Type Field Added",
      { id: "uid", name: customTypeId, type: "UID", zone: "static" },
      { context: { groupId: { Repository: "repoName" } } }
    );

    const saveCustomType = screen.getByText("Save to File System");

    await act(async () => {
      fireEvent.click(saveCustomType);
    });

    await new Promise((r) => setTimeout(r, 1000));

    expect(fakeTracker).toHaveBeenCalledTimes(1);
  });

  test("when the user pushes a custom-type it should send a tracking event", async () => {
    const customTypeId = "a-page";

    server.use(
      rest.get("/api/custom-types/push", (req, res, ctx) => {
        expect(req.url.searchParams.get("id")).toEqual(customTypeId);
        return res(ctx.json({}));
      })
    );

    singletonRouter.push({
      pathname: "cts/[ct]",
      query: { ct: customTypeId },
    });

    const App = render(<CreateCustomTypeBuilder />, {
      preloadedState: {
        environment: {
          framework: "next",
          mockConfig: { _cts: { [customTypeId]: {} } },
        },
        availableCustomTypes: {
          [customTypeId]: {
            local: {
              id: customTypeId,
              label: customTypeId,
              repeatable: true,
              status: true,
              tabs: [
                {
                  key: "Main",
                  value: [],
                },
              ],
            },
          },
        },
        selectedCustomType: {
          model: {
            id: "a-page",
            label: "a-page",
            repeatable: true,
            status: true,
            tabs: [
              {
                key: "Main",
                value: [],
              },
            ],
          },
          initialModel: {
            id: "a-page",
            label: "a-page",
            repeatable: true,
            status: true,
            tabs: [
              {
                key: "Main",
                value: [],
              },
            ],
          },
          mockConfig: {},
          initialMockConfig: {},
        },
      },
    });

    const pushButton = screen.getByText("Push to Prismic");
    await act(async () => {
      fireEvent.click(pushButton);
    });

    await waitFor(() => {
      expect(fakeTracker).toHaveBeenCalledWith(
        "SliceMachine Custom Type Pushed",
        { id: customTypeId, name: customTypeId, type: "repeatable" },
        { context: { groupId: { Repository: "repoName" } } }
      );
    });
  });
});
Example #7
Source File: slices.spec.tsx    From slice-machine with Apache License 2.0 4 votes vote down vote up
describe("slices", () => {
  const fakeTracker = jest.fn().mockImplementation(() => Promise.resolve());

  beforeAll(async () => {
    const div = document.createElement("div");
    div.setAttribute("id", "__next");
    document.body.appendChild(div);

    const fakeAnalytics = jest
      .spyOn(AnalyticsBrowser, "standalone")
      .mockResolvedValue({
        track: fakeTracker,
      } as any);

    await Tracker.get().initialize("foo", "repoName");
    expect(fakeAnalytics).toHaveBeenCalled();
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  beforeEach(async () => {
    mockRouter.setCurrentUrl("/slices");
  });

  test("When user creates a slice it should send a tracking event", async () => {
    const environment = {
      framework: "next",
      mockConfig: { _cts: {} },
    };

    const libraries = [
      {
        path: "./slices",
        isLocal: true,
        name: "slices",
        meta: {
          isNodeModule: false,
          isDownloaded: false,
          isManual: true,
        },
        components: [
          {
            from: "slices",
            href: "slices",
            pathToSlice: "./slices",
            fileName: "index",
            extension: "js",
            screenshotPaths: {},
            mock: [
              {
                variation: "default",
                name: "Default",
                slice_type: "test_slice",
                items: [],
                primary: {
                  title: [
                    {
                      type: "heading1",
                      text: "Cultivate granular e-services",
                      spans: [],
                    },
                  ],
                  description: [
                    {
                      type: "paragraph",
                      text: "Anim in commodo exercitation qui. Elit cillum officia mollit dolore. Commodo voluptate sit est proident ea proident dolor esse ad.",
                      spans: [],
                    },
                  ],
                },
              },
            ],
            model: {
              id: "test_slice",
              type: "SharedSlice",
              name: "TestSlice",
              description: "TestSlice",
              variations: [
                {
                  id: "default",
                  name: "Default",
                  docURL: "...",
                  version: "sktwi1xtmkfgx8626",
                  description: "TestSlice",
                  primary: [
                    {
                      key: "title",
                      value: {
                        type: "StructuredText",
                        config: {
                          single: "heading1",
                          label: "Title",
                          placeholder: "This is where it all begins...",
                        },
                      },
                    },
                    {
                      key: "description",
                      value: {
                        type: "StructuredText",
                        config: {
                          single: "paragraph",
                          label: "Description",
                          placeholder: "A nice description of your feature",
                        },
                      },
                    },
                  ],
                  items: [],
                  imageUrl:
                    "https://images.prismic.io/slice-machine/621a5ec4-0387-4bc5-9860-2dd46cbc07cd_default_ss.png?auto=compress,format",
                },
              ],
            },
            screenshotUrls: {},
            __status: "NEW_SLICE",
          },
        ],
      },
    ];
    const App = render(
      <LibrariesProvider
        env={environment}
        libraries={libraries}
        remoteSlices={[]}
      >
        <SlicesIndex />
      </LibrariesProvider>,
      {
        preloadedState: {
          environment,
          slices: {
            libraries,
            remoteSlices: [],
          },
        },
      }
    );

    const createOneButton = document.querySelector('[data-cy="create-slice"]');
    await act(async () => {
      fireEvent.click(createOneButton);
    });

    const nameInput = document.querySelector('[data-cy="slice-name-input"]');
    await act(async () => {
      fireEvent.change(nameInput, { target: { value: "FooBar" } });
    });

    const submitButton = screen.getByText("Create");
    await act(async () => {
      fireEvent.click(submitButton);
    });

    // very hacky, done because of bug where calling Router.router.push causes issues with re-renders and context
    delete window.location;
    window.location = {} as Location;

    await waitFor(() => {
      expect(fakeTracker).toHaveBeenCalledWith(
        "SliceMachine Slice Created",
        { id: "FooBar", name: "FooBar", library: "slices" },
        { context: { groupId: { Repository: "repoName" } } }
      );
    });
  });
});