solid-testing-library icon indicating copy to clipboard operation
solid-testing-library copied to clipboard

refs are not resolved

Open manast opened this issue 1 year ago • 3 comments

I apologize if this issue is known, or if it does not belong to this repo, but I could not find any answer anywhere, including ChatGPT.

Consider this dummy component:

import { Component, onMount } from "solid-js";

const Button: Component<void> = () => {
  let myButton: HTMLButtonElement;

  onMount(() => {
    console.log({ myButton });
  });

  return <button ref={myButton!}>Text</button>;
};

export default Button;

When running this component, the button element will be printed on the console, however when running the following test the ref is undefined

import { describe, it } from "vitest";
import { render } from "@solidjs/testing-library";
import Button from "./button";

describe("Button Component", () => {
  it("renders correctly", async () => {
    render(() => <Button />);
  });
});

Any ideas?

manast avatar Feb 13 '24 14:02 manast

Effects run asynchronously, so this is expected behavior and not an error. In order to check the ref, you need to await until the button can be found in the DOM.

atk avatar Feb 13 '24 15:02 atk

Effects run asynchronously, so this is expected behavior and not an error. In order to check the ref, you need to await until the button can be found in the DOM.

But thats exactly why onMount is used, to wait for all the components to be mounted in the DOM. Note that the code above is the recommended way to set refs in SolidJS... (and works in the browser perfectly as it should).

manast avatar Feb 14 '24 12:02 manast

I just tested it. I can see the console output: { myButton: HTMLButtonElement {} }. I literally just added your component and test to the ts-vitest template's tests.

atk avatar Feb 14 '24 16:02 atk