Home  >  Q&A  >  body text

How to assert that an element's text is not empty in playwright

<p>I executed this line of code to verify that there is some text on the title. </p> <p><code>await expect(page.locator('div.welcome-content > h2')).not.toBeEmpty;</code></p> <p>But when I execute it, this line of code does nothing, it neither asserts nor returns an error. </p>
P粉675258598P粉675258598429 days ago415

reply all(1)I'll reply

  • P粉018653751

    P粉0186537512023-08-18 00:30:47

    The correct way to use the expect function with the .not.toBeEmpty matcher is to put parentheses after .not.toBeEmpty to call the assertion and compare it with the actual value.

    await expect(page.locator('div.welcome-content > h2')).not.toBeEmpty()
    

    If you are using playwright's own assertion library, you can do this:

    await expect(page.locator('div.welcome-content > h2')).toHaveText(text => text.length > 0);
    
    

    reply
    0
  • Cancelreply