Testcafe get text from element

11,643

Solution 1

From the documentation you want:

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

Solution 2

That will do the trick:

const paragraph      = Selector("p").withText("possible entries");
const extractEntries = await paragraph.textContent;
Share:
11,643
thenewjames
Author by

thenewjames

Recent grad, now a Software Engineer

Updated on July 02, 2022

Comments

  • thenewjames
    thenewjames almost 2 years

    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?

  • Daniel
    Daniel over 2 years
    Excellent, thank you. I kept wrapping my selector to try and clean up the text I was getting. This worked great.