Skip to content

Jest Test: Example Jest Test

Dan Morse edited this page Sep 16, 2021 · 5 revisions

Main Benefits

  1. Allow for an easily repeatable test structure
  2. Improves the stability of the test being run on Travis
  3. Consistent formatting

Code

Example Component

import { render, stopServer, renderWC } from "../../../testing/testing-helpers";
import schema from "../[COMPONENT NAME].schema";
const componentSelector = "bolt-[COMPONENT NAME]";
const { [PROP KEY], [PROP KEY]... } = schema.properties;
let page, fixtures;

afterAll(async () => {
  await stopServer();
  await page.close();
}, 100);

beforeEach(async () => {
  await page.evaluate(() => {
    document.body.innerHTML = "";
  });
});

beforeAll(async () => {
  page = await global.__BROWSER__.newPage();
  await page.goto("http://127.0.0.1:4444/", {
    timeout: 0,
  });

  const defaultData = {
    [DATA THAT ALL THE TEST WILL USE]
  };

  fixtures = {
    defaultData,
  };
});

describe("Bolt [COMPONENT/ELEMENT NAME] [TYPE]", () => {
  // With a Web Component
  test(`default`, async () => {
    const results = await render(
      "@bolt-components-[COMPONENT NAME]/[COMPONENT NAME].twig",
      {
        ...fixtures.defaultData,
      }
    );

    const { innerHTML, outerHTML } = await renderWC(
      componentSelector,
      results.html,
      page
    );

    await expect(results.ok).toBe(true);
    await expect(results.html).toMatchSnapshot();
    await expect(innerHTML).toMatchSnapshot();
    await expect(outerHTML).toMatchSnapshot();
  });

  // Without a Web Component
  test(`default`, async () => {
    const results = await render(
      "@bolt-components-[COMPONENT NAME]/[COMPONENT NAME].twig",
      {
        ...fixtures.defaultData,
      }
    );

    await expect(results.ok).toBe(true);
    await expect(results.html).toMatchSnapshot();
  });
});

describe("Bolt [COMPONENT/ELEMENT NAME] Prop -", () => {
  // Target each of the schema keys with the following pattern
  [PROP KEY].enum.forEach(async (option) => {
    test(`[PROP KEY] items: ${option}`, async () => {
      const results = await render(
        "@bolt-components-[COMPONENT NAME]/[COMPONENT NAME].twig",
        {
          ...fixtures.defaultData,
          [PROP KEY]: option,
        }
      );

      await expect(results.ok).toBe(true);
      await expect(results.html).toMatchSnapshot();
    });
  });
});
Clone this wiki locally