diff --git a/src/server/injected/xpathSelectorEngine.ts b/src/server/injected/xpathSelectorEngine.ts index 41a7be837d..9843ac7f5e 100644 --- a/src/server/injected/xpathSelectorEngine.ts +++ b/src/server/injected/xpathSelectorEngine.ts @@ -18,6 +18,8 @@ import { SelectorEngine, SelectorRoot } from './selectorEngine'; export const XPathEngine: SelectorEngine = { query(root: SelectorRoot, selector: string): Element | undefined { + if (selector.startsWith('/')) + selector = '.' + selector; const document = root instanceof Document ? root : root.ownerDocument; if (!document) return; @@ -29,6 +31,8 @@ export const XPathEngine: SelectorEngine = { }, queryAll(root: SelectorRoot, selector: string): Element[] { + if (selector.startsWith('/')) + selector = '.' + selector; const result: Element[] = []; const document = root instanceof Document ? root : root.ownerDocument; if (!document) diff --git a/test/selectors-misc.spec.ts b/test/selectors-misc.spec.ts index 4dc28f007f..310b314d81 100644 --- a/test/selectors-misc.spec.ts +++ b/test/selectors-misc.spec.ts @@ -184,3 +184,24 @@ it('should escape the scope with >>', async ({ page }) => { await page.setContent(`
`); expect(await page.$eval(`label >> xpath=.. >> input`, e => e.id)).toBe('myinput'); }); + +it('xpath should be relative', async ({ page }) => { + await page.setContent(` + 1 +
+ 2 +
+ `); + expect(await page.$eval(`//*[@class="find-me"]`, e => e.id)).toBe('target1'); + + const div = await page.$('div'); + expect(await div.$eval(`xpath=./*[@class="find-me"]`, e => e.id)).toBe('target2'); + expect(await div.$eval(`xpath=.//*[@class="find-me"]`, e => e.id)).toBe('target2'); + expect(await div.$eval(`//*[@class="find-me"]`, e => e.id)).toBe('target2'); + expect(await div.$eval(`xpath=/*[@class="find-me"]`, e => e.id)).toBe('target2'); + + expect(await page.$eval(`div >> xpath=./*[@class="find-me"]`, e => e.id)).toBe('target2'); + expect(await page.$eval(`div >> xpath=.//*[@class="find-me"]`, e => e.id)).toBe('target2'); + expect(await page.$eval(`div >> //*[@class="find-me"]`, e => e.id)).toBe('target2'); + expect(await page.$eval(`div >> xpath=/*[@class="find-me"]`, e => e.id)).toBe('target2'); +});