Run First Playwright Test

Profile picture for user arilio666

Now that we have successfully installed playwright onto our machine, let's write our first test. We will be doing a simple assertion of the google site with its title name.

  1. Create New Test File
  2. Write First Playwright Test
  3. Run Playwright test
  4. View Playwright Test Report
  5. Video Tutorial

Step 1: Create a new Playwright Test file

Right-click on your test folder and create a new test file with mytestfile.spec.js. You can give any name here, but it should end with .spec.js

create new playwright test file

Step 2: Write First Playwright Test

Paste below code in above created file.

const {test, expect} = require('@playwright/test');

test('Google Title Assertion', async ({page})=> 
    await page.goto("");
    await expect(page).toHaveTitle("Google");

Require and const statement 

const {test, expect} = require('@playwright/test');
  • First, import test and expect libraries from @playwright/test module and declare two instances of test and expect library using const. 
  • We are using the const JavaScript variable here, which has the block-level scope and cannot be updated or re-declared into the scope.
  • Here we are using {} which is destructuring pattern for assignment.

test function

test('Google Title Assertion', ()=> 

  • In the first argument 'Google Title Assertion' is Test Title and in 2nd argument we declared JavaScript anonymous arrow function using () => {}

page fixture and instance

test('Google Title Assertion', ({page})=> 
  • page fixture provides page object that is available to the test. This is the most commonly used fixture in a test. 
  • Pass page instance as an argument in the arrow function.
  • Use the goto method visit to the website URL.



async and await 

  • Arrow function is declared async, and await keyword is used before statements because JavaScript is asynchronous. It tries to run several steps at once irrespective of sequence, so await has to be used to avoid this.
  • We must wait for one step to execute successfully before running the other; otherwise, the tests can go flaky. In our test, once we visit the page then, only we can verify the title.

Step 3: Run Your Playwright test

By default Playwright test runs in headless mode for 3 browsers chromium, firefox and webkit. To run test in visual mode add --headed.

$ npx playwright test --headed

In case your steps failed it will automatically open the report for your otherwise jump to step 4.

Step 4: View Playwright Test Report

We can view the reports of the last ran test case by using this command.

$ npx playwright show-report

Video Tutorial: Playwright First Test