Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

document.activeElement state lost after rendering #317

Open
kristiankostadinov opened this issue Jun 25, 2024 · 0 comments
Open

document.activeElement state lost after rendering #317

kristiankostadinov opened this issue Jun 25, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@kristiankostadinov
Copy link

kristiankostadinov commented Jun 25, 2024

Describe the bug

A component focuses an element in the onMounted hook and the focus is lost after the render function.

In the Codesandbox there is a TestButton component that sets the focus in onMounted. In the respective test there are two test cases - one using @testing-library/vue and one using @vue/test-utils directly. The behavior of document.activeElement differs between the two.
@testing-library/vue loses the state of document.activeElement

To Reproduce Steps to reproduce the behavior:

Codesandbox

Expected behavior

document.activeElement should be the button that was focused in the onMounted hook

Screenshots

image

Related information:

  • @testing-library/vue version: 8.1.0
  • Vue version: 3.4.15
  • node version: v20.12.0
  • npm (or yarn) version: npm 10.5.0

Relevant code or config (if any)

TestButton.vue

<template>
  <div>
    <button ref="button">Test</button>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";

const button = ref<HTMLButtonElement | null>(null);

onMounted(() => {
  console.info(document.activeElement?.nodeName); // <- body
  button.value?.focus();
  console.info(document.activeElement?.nodeName); // <- button
});
</script>
import { render } from "@testing-library/vue";
import { mount } from "@vue/test-utils";
import TestButton from "./TestButton.vue";

describe("TestButton", () => {
  it("test @vue/test-utils", () => {
    const wrapper = mount(TestButton, { attachTo: document.body });

    console.info(document.activeElement?.nodeName); // <- button
    expect(document.activeElement?.nodeName).toBe("BUTTON");

    wrapper.unmount();
  });

  it("test @testing-library/vue", () => {
    const { unmount } = render(TestButton, { container: document.body });

    console.info(document.activeElement?.nodeName); // <- (!) body
    expect(document.activeElement?.nodeName).toBe("BUTTON");

    unmount();
  });
});
@kristiankostadinov kristiankostadinov added the bug Something isn't working label Jun 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant