Search code examples
javascriptautomated-testse2e-testingweb-testingtestcafe

Testcafe get text from element


I'm trying to get a text from a modal on Chrome. Using the console, I can get the inner text as follows:

document.querySelector('.my-form > a').innerText
// returns http://a-url.com

Now, on my test, I can evaluate the element using

const myText = Selector('.my-form > a').innerText;
await t
  .expect(myText).contains('url');

and I can even click on that URL

await t.click(myText);

but I cannot put that inner text to a variable, for instance. I tried using a ClientFunction from this post

const getUrl = ClientFunction(() => document.querySelector('.my-form > a').innerText);

test('My Test', async t => {
const text = await getUrl();
console.log(text);
});

// this results in 
// TypeError: Cannot read property 'innerText' of null

and tried using a plain Selector as this post suggests

const text = Selector('.my-form > a').innerText;
const inner = await text.textContent;
console.log(inner);

// prints: undefined

How to extract a text from an element? I understand that t.selectText is limited in this scenario, right?


Solution

  • From the documentation you want:

    const text = await Selector('.my-form > a').innerText;