Search code examples
c#playwrightplaywright-dotnet

How to get the text that was inputted by a user in a text box using Playwright for C#


I am using Playwright in C#. I have a text box:

<input id="NameFirst" name="NameFirst" type="text" >

In my Playwright test, I need to check to see if the name populating the text box is equal to the string "firstName".

This is what I have tried (along with practically every other Playwright assertion): await Expect(RMSPage.Locator("#NameFirst")).ToContainTextAsync("firstName");

Here is the error I am receiving:

Microsoft.Playwright.PlaywrightException : Locator expected to contain text 'firstName'
But was: ''

Solution

  • What you want is to get the value of the input. You need to use ToHaveValueAsync

    await Expect(RMSPage.Locator("#NameFirst")).ToHaveValueAsync("firstName");
    

    Sometimes the values of an element is in placeholder / Value attribute and sometime as text.

    So based on situation we can use

    ToHaveAttributeAsync("type", "text");
    ToContainTextAsync("substring")
    ToHaveTextAsync(new Regex("Welcome, Test User"));