Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert for errors in Playwright?

I'm going nuts trying to assert for a known TimeoutError. I'm currently testing for the Hidden Layers scenario from UI Testing Playground in Playwright Node.js and I would like to know if it's possible to have the TimeoutError not to fail the test, as this is the expectation. I'm pretty new in automating with both Playwright and Typescript.

I have tried multiple methods even making the clickGreenButton() method throw the error, but it seems the expect() function does not catch it at all.

Method inside the HiddenLayersPage.ts:

    async clickGreenButton() {
        await this.greenButton.click()
    }

Code inside the spec file which is supposed to check that the second click would not be successful as the element to be clicked becomes hidden:

await hiddenLayersPage.clickGreenButton();
expect(async () => await hiddenLayersPage.clickGreenButton()).toThrow();
like image 813
aandrei1991 Avatar asked Aug 03 '26 06:08

aandrei1991


1 Answers

This is happening because expect is running your function, but being async it’s getting a promise (albeit rejected) back, rather than an error/exception.

So the syntax is a little different. You just need to pass expect the resulting promise, tell it to unwrap the promise with .rejects, and then call toThrow, like so:

await expect(hiddenLayersPage.clickGreenButton()).rejects.toThrow();

Notice the usage/placement of await, since you need to await the async matcher, but not await the function since you want the promise.

like image 195
David R Avatar answered Aug 06 '26 07:08

David R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!