solid-testing-library
solid-testing-library copied to clipboard
refs are not resolved
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?
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.
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).
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.