I am testing html header orders in the following code, derived from this answer. But, test stops when it hits the first error. I want to get all errors on the page instead of getting first error and stops
I need to improve my code for it
async assertHtmlHeadingOrders() {
await this.page.waitForLoadState('domcontentloaded')
const failMsg = (prev, curr) =>
`h${curr} was more than one level deeper than previous header h${prev}`
const headers = await this.page
.locator('h1, h2, h3, h4, h5, h6')
.evaluateAll(els => els.map(el => +el.tagName.slice(1)))
// eslint-disable-next-line no-plusplus, id-length
for (let i = 1; i < headers.length; i++) {
expect(headers[i] - headers[i - 1], failMsg(headers[i - 1], headers[i])).toBeLessThan(2)
}
}
You can put the failing pairs into an array, then assert one time on the whole array, enabling a clearer error message.
Output:
The same suggestions as in this previous answer apply: adding a custom matcher or polling, as fits your needs.
Adding a custom matcher would abstract away the logic shown here into the matcher rather than into functions, which is a bit more elegant for the caller. If you're using this on many tests, it's probably worth the extra work. Here's an example that also polls to ensure the test eventually passes:
Now the assertion failure is clearer, and we can also work with pages that add more headers after navigation:
Here's a simpler custom matcher that doesn't include polling, which is better if you only want to check headers at page load, or want to explicitly use a poll in the test: