Skip to content

Commit

Permalink
Added testWithEffect
Browse files Browse the repository at this point in the history
  • Loading branch information
Hugos68 committed Apr 13, 2024
1 parent 3a0cc45 commit 7be0682
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 17 deletions.
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
import { describe, expect, it } from "vitest";

Check failure on line 1 in packages/runed/src/lib/functions/useActiveElement/useActiveElement.test.svelte.ts

View workflow job for this annotation

GitHub Actions / Lint

'it' is defined but never used
import { tick } from "svelte";
import { useActiveElement } from "./index.js";
import { testWithEffect } from "$lib/test/util.svelte.js";

describe("useActiveElement", () => {
it("initializes with `document.activeElement`", () => {
const cleanup = $effect.root(() => {
const activeElement = useActiveElement();
expect(activeElement.value).toBe(document.activeElement);
});
cleanup();
testWithEffect("initializes with `document.activeElement`", () => {
const activeElement = useActiveElement();
expect(activeElement.value).toBe(document.activeElement);
});
it("updates accordingly when `document.activeElement` element changes", () => {
const input = document.createElement("input");
const cleanup = $effect.root(() => {
const activeElement = useActiveElement();
testWithEffect(
"updates accordingly when `document.activeElement` element changes",
async () => {
const input = document.createElement("input");
document.body.appendChild(input);
input.focus();
requestAnimationFrame(() => {
expect(document.activeElement).toBe(input);
expect(activeElement.value).toBe(input);
});
});
cleanup();
});

const activeElement = useActiveElement();
await tick();
expect(document.activeElement).toBe(input);
expect(activeElement.value).toBe(input);
}
);
});
13 changes: 13 additions & 0 deletions packages/runed/src/lib/test/util.svelte.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { it } from "vitest";

export function testWithEffect(name: string, fn: () => void) {
it(name, async () => {
let promise: Promise<void> | void;
const cleanup = $effect.root(() => (promise = fn()));
try {
await promise!;
} finally {
cleanup();
}
});
}

0 comments on commit 7be0682

Please sign in to comment.