Opening and Validating a Page

Exploring Playwright and TypeScript

Welcome to the first lesson of our course on automated testing with Playwright and TypeScript. In this lesson, we’ll start with the basics: opening a web page and validating its title. This is a crucial step, as it helps us confirm that our automation scripts can successfully navigate to the desired web page.

What You'll Learn

In this lesson, we will cover how to use Playwright to open a page and validate its title. We will do this using TypeScript, a powerful language that helps catch errors early through its strong typing. Specifically, you will learn how to:

  1. Use Playwright to automate browser actions.
  2. Navigate to a specific URL.
  3. Capture and validate the page title.

Here's a short code snippet to give you an idea:

import { test, expect } from '@playwright/test';

test('open and validate a page', async ({ page }) => {
  await page.goto('http://localhost:3000');
  const pageTitle = await page.title();
  expect(pageTitle).toBe("BookStore");
});

In the above code, we are instructing Playwright to open a web page running on http://localhost:3000 and then validate that the title of the page is "BookStore."

Code Explanation

  1. Importing Modules:

    import { test, expect } from '@playwright/test';

    In TypeScript, certain commands and features are built-in and can be used directly. However, for specialized functionalities like automated testing, we rely on additional libraries. Importing allows us to bring in these specialized features. In this case, we import test and expect from the @playwright/test module. The test function lets us define and organize test cases, while expect provides a set of assertions to validate test conditions.

  2. Defining a Test:

    test('open and validate a page', async ({ page }) => {

    Here, we define a test with a descriptive name 'open and validate a page'. The async keyword indicates that the function contains asynchronous operations. The page object provided by Playwright represents a new browser tab.

  3. Navigating to the URL:

    await page.goto('http://localhost:3000');

    This command instructs the browser to navigate to http://localhost:3000, which is the local address where your application is expected to be running during tests. In local development, apps are commonly run on port 3000.

  4. Capturing and Validating the Page Title:

    const pageTitle = await page.title();
    expect(pageTitle).toBe("BookStore");

    We use the title() method to get the title of the page and store it in the pageTitle variable. The expect function asserts that the title is "BookStore".

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal