Testcafe get text from element

thenewjames picture thenewjames · Mar 21, 2019 · Viewed 7.4k times · Source

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?

Answer

ioseph picture ioseph · Mar 25, 2019

From the documentation you want:

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