Search code examples
typescriptui-automationplaywright

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();

Solution

  • 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.