Skip to content
FrontDepth, Home

Back to the topic

Practice: Testing UI the way users use it

Answer first, then compare. Rate yourself honestly — it drives your weak-areas list.

3 predict-output · 3 open

Questions up to level

Shows questions up to the selected level.

No practice questions for this level yet.

  1. Predict the outputJunior

    This is a plain-JS simulation of Testing Library's query rules, not the library itself: page lists each element's role and accessible name. A string name must match the whole name exactly, a RegExp may match part of it. getByRole throws when nothing or more than one element matches; queryByRole returns null when nothing matches but still throws on several. The real error messages are longer. What does it log?

    JavaScript
    const page = [
      { role: "heading", name: "Your cart" },
      { role: "button", name: "Remove Trail backpack" },
      { role: "button", name: "Remove Rain jacket" },
      { role: "button", name: "Checkout" },
    ];
    
    function queryAllByRole(role, name) {
      return page.filter(
        (el) =>
          el.role === role &&
          (name === undefined || (name instanceof RegExp ? name.test(el.name) : el.name === name)),
      );
    }
    
    function getByRole(role, name) {
      const found = queryAllByRole(role, name);
      if (found.length === 0) throw new Error("no match");
      if (found.length > 1) throw new Error("multiple matches");
      return found[0];
    }
    
    function queryByRole(role, name) {
      const found = queryAllByRole(role, name);
      if (found.length > 1) throw new Error("multiple matches");
      return found[0] ?? null;
    }
    
    function run(label, query) {
      try {
        const element = query();
        console.log(label + ": " + (element === null ? "null" : element.name));
      } catch (error) {
        console.log(label + ": throws, " + error.message);
      }
    }
    
    run("A", () => getByRole("button", "Checkout"));
    run("B", () => getByRole("button", "checkout"));
    run("C", () => queryByRole("alert"));
    run("D", () => queryByRole("button", /remove/i));
    run("E", () => getByRole("button", /rain/i));
    console.log("F: " + queryAllByRole("button", /remove/i).length);
  2. Open questionJunior

    What does "test the way users use the software" mean for a React component test, and which queries does it lead you to?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  3. Predict the outputMiddle

    A plain-JS simulation of how Testing Library and jest-dom match text, not the libraries themselves. normalize is the default normalizer: it trims the text and collapses runs of whitespace into one space. getByTextMatches models getByText: it sees only the element's own text nodes, and a string must equal the whole text unless exact is false, which makes it a case-insensitive substring match. toHaveTextContent models the jest-dom matcher: it reads the full textContent, and a string is a substring match. What does it log?

    JavaScript
    const normalize = (text) => text.trim().replace(/\s+/g, " ");
    
    function getByTextMatches(ownText, matcher, exact = true) {
      const text = normalize(ownText);
      if (matcher instanceof RegExp) return matcher.test(text);
      return exact ? text === matcher : text.toLowerCase().includes(matcher.toLowerCase());
    }
    
    function toHaveTextContent(textContent, expected) {
      const text = normalize(textContent);
      return expected instanceof RegExp ? expected.test(text) : text.includes(expected);
    }
    
    // <span>  Free   delivery </span>
    const badge = { ownText: "  Free   delivery ", textContent: "  Free   delivery " };
    // <p>Total: <strong>$40</strong></p>
    const total = { ownText: "Total: ", textContent: "Total: $40" };
    
    console.log(getByTextMatches(badge.ownText, "Free delivery"));
    console.log(getByTextMatches(badge.ownText, "free delivery"));
    console.log(getByTextMatches(badge.ownText, "free", false));
    console.log(getByTextMatches(total.ownText, "Total: $40"));
    console.log(getByTextMatches(total.ownText, "Total:"));
    console.log(toHaveTextContent(total.textContent, "$4"));
    console.log(toHaveTextContent(total.textContent, /^Total: \$4$/));
  4. Open questionMiddle

    How would you test a form that shows a validation message for an invalid email address?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  5. Predict the outputSenior

    A plain-JS simulation of the checks jest-dom's toBeVisible() makes, not the library itself: an element is visible when neither it nor any ancestor has the hidden attribute, display: none, visibility: hidden or collapse, or opacity: 0. cssLoaded models whether the stylesheet reaches the test document. Under Vitest's default settings it does not: imported CSS files are replaced with empty strings, so only inline styles count. What does it log?

    JavaScript
    const stylesheet = { "is-collapsed": { display: "none" } };
    
    function computedStyle(el, cssLoaded) {
      const fromClasses = cssLoaded ? el.classes.map((name) => stylesheet[name] ?? {}) : [];
      return Object.assign({ display: "block", visibility: "visible", opacity: "1" }, ...fromClasses, el.style);
    }
    
    function isVisible(el, cssLoaded) {
      if (el === null) return true;
      const style = computedStyle(el, cssLoaded);
      const shown =
        !el.hidden &&
        style.display !== "none" &&
        style.visibility !== "hidden" &&
        style.visibility !== "collapse" &&
        style.opacity !== "0";
      return shown && isVisible(el.parent, cssLoaded);
    }
    
    const make = (props) => ({ classes: [], style: {}, hidden: false, parent: null, ...props });
    const panel = make({ classes: ["is-collapsed"] });
    const answer = make({ parent: panel });
    const ghost = make({ style: { opacity: "0" } });
    const drawer = make({ hidden: true });
    const offscreen = make({ style: { position: "absolute", left: "-9999px" } });
    
    console.log("answer without CSS: " + isVisible(answer, false));
    console.log("answer with CSS: " + isVisible(answer, true));
    console.log("ghost: " + isVisible(ghost, false));
    console.log("drawer: " + isVisible(drawer, false));
    console.log("offscreen: " + isVisible(offscreen, true));
  6. Open questionSenior

    Your component tests run in jsdom. What can they not tell you, and how do you decide what to test in a real browser instead?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.