thenewjames
thenewjames

Reputation: 1164

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?

Upvotes: 7

Views: 18445

Answers (2)

Zhivko.Kostadinov
Zhivko.Kostadinov

Reputation: 467

That will do the trick:

const paragraph      = Selector("p").withText("possible entries");
const extractEntries = await paragraph.textContent;

Upvotes: 2

ioseph
ioseph

Reputation: 1917

From the documentation you want:

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

Upvotes: 12

Related Questions