Hooks in Playwright Test are an important piece if functionality.
In the tutorial video, Jared from "Commit Quality" explains how to use hooks in Playwright. He points out the four main types of hooks in this automated testing tool: beforeEach, afterEach, beforeAll, and afterAll. As their names suggest, these hooks are executed before and after individual tests, or once before or after all tests in a test file.
Jared provides detailed code examples to demonstrate how these hooks work. He first creates two tests that involve an assertion of a number variable 'x'.
Then, Jared introduces the beforeEach and beforeAll hooks and how they can be used in general testing scope. By calling a simple console.log command in each of the hooks, he demonstrates the execution sequence of these hooks in relation to the tests. It is shown that the beforeEach hook gets executed before each individual test, whereas the beforeAll hook runs just once before all tests.
To further illustrate the utilization of hooks, Jared adds afterEach and afterAll hooks in the following segment. He proves that these hooks act after the tests run, similar to the beforeEach and beforeAll counterparts, but take action upon completion of the tests instead.
The video also covers applying these hooks in describe blocks to enhance the scope and efficiency of the code. Jared moves his tests into two separate describe blocks ('Group 1' and 'Group 2'). He then sets a different value for 'x' in a beforeAll hook for each group, eliminating repeated code within tests. This method conveniently adjusts 'x' to the required value for the tests in each group. It is demonstrated that these hooks are executed only for the tests within a same describe block.
In conclusion, hooks can be leveraged to set up and tear down tests in more readable, maintainable and efficient manner. As a side note, Jared also mentions that Playwright recommends the use of fixtures over hooks for more flexible and better structured automation testing, which he indicates will be the subject of his next tutorial video.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].