Skip to content

Commit a051a3b

Browse files
ShaulLavoclaude
andcommitted
fix: ensure stable testid on baseElement and container
Port upstream fix from vitest-browser-react (vitest-community#42, vitest-community#44, vitest-community#45) to prevent flaky locators when baseElement/container lack a testid attribute. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent cad8e30 commit a051a3b

1 file changed

Lines changed: 14 additions & 1 deletion

File tree

src/pure.tsx

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type {
33
LocatorSelectors,
44
PrettyDOMOptions,
55
} from 'vitest/browser'
6-
import { page, utils } from 'vitest/browser'
6+
import { page, server, utils } from 'vitest/browser'
77
import {
88
createRoot,
99
getOwner,
@@ -16,6 +16,14 @@ import type { JSX } from 'solid-js'
1616

1717
const { debug, getElementLocatorSelectors } = utils
1818

19+
let idx = 0
20+
function ensureTestIdAttribute(element: HTMLElement) {
21+
const attributeId = server.config.browser.locators.testIdAttribute
22+
if (!element.hasAttribute(attributeId)) {
23+
element.setAttribute(attributeId, `__vitest_${idx++}__`)
24+
}
25+
}
26+
1927
export interface RenderResult extends LocatorSelectors {
2028
container: HTMLElement
2129
baseElement: HTMLElement
@@ -56,6 +64,11 @@ export function render(
5664
container = baseElement.appendChild(document.createElement('div'))
5765
}
5866

67+
// Ensuring testid attributes exist so that the generated locators will be stable
68+
// https://github.com/vitest-community/vitest-browser-react/issues/42
69+
ensureTestIdAttribute(baseElement)
70+
ensureTestIdAttribute(container)
71+
5972
// Dispose previous root if it exists on the same container
6073
const prevDispose = mountedRoots.get(container)
6174
if (prevDispose) {

0 commit comments

Comments
 (0)