Skip to content

[📖] How to do unit testing of components with Vite if the testing env is JSDOM instead of node #3560

Open
@Nedimko123

Description

@Nedimko123

Suggestion

If my component has any javascript that needs to be loaded on the client side, the test fails for me like if I wanted to check if window.width > 1024, it wouldnt work with vitest. Everybody suggests using jsdom, so I tried that like this:


import { renderToString } from "@builder.io/qwik/server";
import { test, expect, vi } from "vitest";
import { ExampleTest } from "./example";

test(`[ExampleTest Component]: Click counter +1`, async () => {
  const jsdom = require("jsdom");
  const { JSDOM } = jsdom;

  const screen = await renderToString(
    <body>
      <ExampleTest flag={false} />
    </body>
  );
  const dom = new JSDOM(screen.html);

  const button = dom.window.document.querySelector("button.btn-counter");

  expect(dom.window.document.querySelector("span").textContent).toBe("Count:0");
  expect(dom.window.document.querySelector("div.icon").textContent).toBe(
    "Flag: 💣"
  );
  button.addEventListener("click", () => {
    // const countElement = dom.window.document.querySelector("span");
    // const count = parseInt(countElement.textContent.replace("Count:", ""), 10);
    // countElement.textContent = `Count:${count + 1}`;
  });

  console.log(button.click());

  console.log(dom.window.document.querySelector("span").textContent);
});

This isn't that native and button clicks do not work for the example component, only if I add the event listener and I do something in that event listener - that will happen, but the onClick function will not.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions