Search code examples
javascriptangulartypescriptplaywright

Typescript (playwright) how to match partially from array values?


I'm using playwright to test some table data, some of which includes a datetime. This datetime includes a timestamp, which can change based on when the data has changed. I don't care too much about the timestamp, just the day it was last modified. I'm looking for a way in my expect().toHaveText(['string array here']) to ignore the timestamp. See code example below:

This fails because I'm not expecting the time stamp.

const tableRowData = this.page.locator(`//table[@class="myTableClass"]//td`)  //['John', 'Smith', 'Ohio', 'Aug 22, 2023 09:44 AM EST']
await expect(tableRowData).toHaveText('John', 'Smith', 'Ohio', 'Aug 22, 2023');

Due to timing, or delays in updates in the database, I don't want to try and test the timestamp to the minute/second, the day is sufficient. Is there a good way to do this in the toHaveText() expect method? I'm pretty sure I can do something that looks at the nth td tag, using regular expressions to return a string without the timestamp, but I was hoping to keep the test looking cleaner but just using toHaveText() with a string array in it.

For example:

const tableRowData = this.page.locator(`//table[@class="myTableClass"]//td`).nth(3) //'Aug 22, 9:44 AM EST
const dataWithoutTimeStamp = getDateWithoutTimeStamp(tableRowData) // Regex in this method to return only 'Aug 22, 2023'
expect(dataWithoutTimeStamp).toHaveText('Aug 22, 2023');

My goal is to avoid having to check each td value individually, for example:

expect(firstTd).toHaveText('John');
expect(secondTd).toHaveText('Smith');
// ... 10 more td's
expect(dataWithoutTimeStamp).toHaveText('Aug 22, 2023');

Thanks in advance!


Solution

  • In playwright how to match partially from array values?

    Use toContainText:

    toContainText matches partial text in the array compared to toHaveText which expects full text to match in the array.

    await expect(tableRowData).toContainText('John', 'Smith', 'Ohio', 'Aug 22, 2023');
    

    If you pass an array as an expected value, for toContainText the expectations are:

    • Locator resolves to a list of elements.
    • Elements from a subset of this list contain text from the expected array, respectively.
    • The matching subset of elements has the same order as the expected array.
    • Each text value from the expected array is matched by some element from the list.