docs: improve dotnet getting started (#30594)

This commit is contained in:
Debbie O'Brien 2024-05-02 12:06:39 +02:00 committed by GitHub
parent 980f9c6ad4
commit bf11c95d58
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 322 additions and 324 deletions

View file

@ -148,7 +148,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Setup dotnet
uses: actions/setup-dotnet@v3
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x
- run: dotnet build
@ -266,7 +266,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Setup dotnet
uses: actions/setup-dotnet@v3
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x
- run: dotnet build
@ -370,7 +370,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Setup dotnet
uses: actions/setup-dotnet@v3
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x
- run: dotnet build
@ -388,23 +388,49 @@ jobs:
Once you have your [GitHub actions workflow](#setting-up-github-actions) setup then all you need to do is [Create a repo on GitHub](https://docs.github.com/en/get-started/quickstart/create-a-repo) or push your code to an existing repository. Follow the instructions on GitHub and don't forget to [initialize a git repository](https://github.com/git-guides/git-init) using the `git init` command so you can [add](https://github.com/git-guides/git-add), [commit](https://github.com/git-guides/git-commit) and [push](https://github.com/git-guides/git-push) your code.
######
* langs: js, java, python
<img width="861" alt="Create a Repo and Push to GitHub" src="https://user-images.githubusercontent.com/13063165/183423254-d2735278-a2ab-4d63-bb99-48d8e5e447bc.png"/>
######
* langs: csharp
![dotnet repo on github](https://github.com/microsoft/playwright/assets/13063165/4f1b4cc3-b850-4d60-a99e-24057eaf91ad)
## Opening the Workflows
Click on the **Actions** tab to see the workflows. Here you will see if your tests have passed or failed.
<img width="847" alt="Opening the Workflows" src="https://user-images.githubusercontent.com/13063165/183423584-2ea18038-cd49-4daa-a20c-2205352f0933.png"/>
######
* langs: js, python, java
![opening the workflow](https://user-images.githubusercontent.com/13063165/183423783-58bf2008-514e-4f96-9c12-c9a55703960c.png)
######
* langs: csharp
![opening the workflow](https://github.com/microsoft/playwright/assets/13063165/71793c09-0815-4faa-866b-85684a1f87e5)
On Pull Requests you can also click on the **Details** link in the [PR status check](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/collaborating-on-repositories-with-code-quality-features/about-status-checks).
<img width="645" alt="pr status checked" src="https://user-images.githubusercontent.com/13063165/183722462-17a985db-0e10-4205-b16c-8aaac36117b9.png" />
## Viewing Test Logs
Clicking on the workflow run will show you the all the actions that GitHub performed and clicking on **Run Playwright tests** will show the error messages, what was expected and what was received as well as the call log.
<img width="839" alt="Viewing Test Logs" src="https://user-images.githubusercontent.com/13063165/183423783-58bf2008-514e-4f96-9c12-c9a55703960c.png"/>
######
* langs: js, python, java
![Viewing Test Logs](https://user-images.githubusercontent.com/13063165/183423783-58bf2008-514e-4f96-9c12-c9a55703960c.png)
######
* langs: csharp
![viewing the test logs](https://github.com/microsoft/playwright/assets/13063165/ba2d8d7b-ffce-42de-95e0-bcb35c421975)
## HTML Report
@ -441,12 +467,22 @@ Once you have served the report using `npx playwright show-report`, click on the
![playwright trace viewer](https://github.com/microsoft/playwright/assets/13063165/10fe3585-8401-4051-b1c2-b2e92ac4c274)
## Viewing the Trace
* langs: python, java, csharp
* langs: python, java
[trace.playwright.dev](https://trace.playwright.dev) is a statically hosted variant of the Trace Viewer. You can upload trace files using drag and drop.
![playwright trace viewer](https://github.com/microsoft/playwright/assets/13063165/6d5885dc-d511-4c20-b728-040a7ef6cea4)
## Viewing the Trace
* langs: csharp
You can upload Traces which get created on your CI like GitHub Actions as artifacts. This requires [starting and stopping the trace](./trace-viewer-intro#recording-a-trace). We recommend only recording traces for failing tests. Once your traces have been uploaded to CI, they can then be downloaded and opened using [trace.playwright.dev](https://trace.playwright.dev), which is a statically hosted variant of the Trace Viewer. You can upload trace files using drag and drop.
######
* langs: csharp
![playwright trace viewer](https://github.com/microsoft/playwright/assets/13063165/84150084-5019-470a-8449-b61d206bfbb0)
## Publishing report on the web
* langs: js

View file

@ -29,7 +29,7 @@ playwright codegen demo.playwright.dev/todomvc
```
```bash csharp
pwsh bin/Debug/netX/playwright.ps1 codegen demo.playwright.dev/todomvc
pwsh bin/Debug/net8.0/playwright.ps1 codegen demo.playwright.dev/todomvc
```
### Recording a test

View file

@ -69,13 +69,13 @@ dotnet add package Microsoft.Playwright.MSTest
dotnet build
```
4. Install required browsers by replacing `netX` with the actual output folder name, e.g. `net8.0`:
1. Install required browsers. This example uses `net8.0`, if you are using a different version of .NET you will need to adjust the command and change `net8.0` to your version.
```bash
pwsh bin/Debug/netX/playwright.ps1 install
pwsh bin/Debug/net8.0/playwright.ps1 install
```
If `pwsh` is not available, you have to [install PowerShell](https://docs.microsoft.com/powershell/scripting/install/installing-powershell).
If `pwsh` is not available, you will have to [install PowerShell](https://docs.microsoft.com/powershell/scripting/install/installing-powershell).
## Add Example Tests
@ -102,28 +102,28 @@ namespace PlaywrightTests;
[Parallelizable(ParallelScope.Self)]
[TestFixture]
public class Tests : PageTest
public class ExampleTest : PageTest
{
[Test]
public async Task HomepageHasPlaywrightInTitleAndGetStartedLinkLinkingtoTheIntroPage()
public async Task HasTitle()
{
await Page.GotoAsync("https://playwright.dev");
// Expect a title "to contain" a substring.
await Expect(Page).ToHaveTitleAsync(new Regex("Playwright"));
}
// create a locator
var getStarted = Page.GetByRole(AriaRole.Link, new() { Name = "Get started" });
// Expect an attribute "to be strictly equal" to the value.
await Expect(getStarted).ToHaveAttributeAsync("href", "/docs/intro");
[Test]
public async Task GetStartedLink()
{
await Page.GotoAsync("https://playwright.dev");
// Click the get started link.
await getStarted.ClickAsync();
await Page.GetByRole(AriaRole.Link, new() { Name = "Get started" }).ClickAsync();
// Expects the URL to contain intro.
await Expect(Page).ToHaveURLAsync(new Regex(".*intro"));
}
// Expects page to have a heading with the name of Installation.
await Expect(Page.GetByRole(AriaRole.Heading, new() { Name = "Installation" })).ToBeVisibleAsync();
}
}
```
@ -140,28 +140,28 @@ using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace PlaywrightTests;
[TestClass]
public class UnitTest1 : PageTest
public class ExampleTest : PageTest
{
[TestMethod]
public async Task HomepageHasPlaywrightInTitleAndGetStartedLinkLinkingtoTheIntroPage()
public async Task HasTitle()
{
await Page.GotoAsync("https://playwright.dev");
// Expect a title "to contain" a substring.
await Expect(Page).ToHaveTitleAsync(new Regex("Playwright"));
}
// create a locator
var getStarted = Page.GetByRole(AriaRole.Link, new() { Name = "Get started" });
// Expect an attribute "to be strictly equal" to the value.
await Expect(getStarted).ToHaveAttributeAsync("href", "/docs/intro");
[TestMethod]
public async Task GetStartedLink()
{
await Page.GotoAsync("https://playwright.dev");
// Click the get started link.
await getStarted.ClickAsync();
await Page.GetByRole(AriaRole.Link, new() { Name = "Get started" }).ClickAsync();
// Expects the URL to contain intro.
await Expect(Page).ToHaveURLAsync(new Regex(".*intro"));
}
// Expects page to have a heading with the name of Installation.
await Expect(Page.GetByRole(AriaRole.Heading, new() { Name = "Installation" })).ToBeVisibleAsync();
}
}
```
@ -170,33 +170,13 @@ public class UnitTest1 : PageTest
## Running the Example Tests
By default tests will be run on Chromium. This can be configured via the `BROWSER` environment variable, or by adjusting the [launch configuration options](./test-runners.md). Tests are run in headless mode meaning no browser will open up when running the tests. Results of the tests and test logs will be shown in the terminal.
<Tabs
groupId="test-runners"
defaultValue="nunit"
values={[
{label: 'NUnit', value: 'nunit'},
{label: 'MSTest', value: 'mstest'}
]
}>
<TabItem value="nunit">
By default tests will be run on Chromium. This can be configured via the `BROWSER` environment variable, or by adjusting the [launch configuration options](./running-tests.md). Tests are run in headless mode meaning no browser will open up when running the tests. Results of the tests and test logs will be shown in the terminal.
```bash
dotnet test -- NUnit.NumberOfTestWorkers=5
dotnet test
```
</TabItem>
<TabItem value="mstest">
```bash
dotnet test -- MSTest.Parallelize.Workers=5
```
</TabItem>
</Tabs>
See our doc on [Test Runners](./test-runners.md) to learn more about running tests in headed mode, running multiple tests, running specific configurations etc.
See our doc on [Running and Debugging Tests](./running-tests.md) to learn more about running tests in headed mode, running multiple tests, running specific configurations etc.
## System requirements
@ -209,7 +189,7 @@ See our doc on [Test Runners](./test-runners.md) to learn more about running tes
- [Write tests using web first assertions, page fixtures and locators](./writing-tests.md)
- [Run single test, multiple tests, headed mode](./running-tests.md)
- [Learn more about the NUnit and MSTest base classes](./test-runners.md)
- [Generate tests with Codegen](./codegen.md)
- [See a trace of your tests](./trace-viewer-intro.md)
- [Using Playwright as library](./library.md)
- [Run tests on CI](./ci-intro.md)
- [Learn more about the NUnit and MSTest base classes](./test-runners.md)

View file

@ -7,57 +7,130 @@ title: "Running and debugging tests"
You can run a single test, a set of tests or all tests. Tests can be run on different browsers. By default, tests are run in a headless manner, meaning no browser window will be opened while running the tests and results will be seen in the terminal. If you prefer, you can run your tests in headed mode by using the `headless` test run parameter.
- Running all tests
**You will learn**
```bash
dotnet test
```
- [How to run tests](/running-tests)
- [How to debug tests](/running-tests.md#debugging-tests)
- Running a single test file
## Running tests
```bash
dotnet test --filter "MyClassName"
```
### Run all tests
- Run a set of test files
Use the following command to run all tests.
```bash
dotnet test --filter "MyClassName1|MyClassName2"
```
```bash
dotnet test
```
- Run the test with the title
### Run your tests in headed mode
```bash
dotnet test --filter "Name~TestMethod1"
```
Use the following command to run your tests in headed mode opening a browser window for each test.
- Running Tests on specific browsers
```bash tab=bash-bash lang=csharp
HEADED=1 dotnet test
```
```bash
dotnet test -- Playwright.BrowserName=webkit
```
```batch tab=bash-batch lang=csharp
set HEADED=1
dotnet test
```
- Running Tests on multiple browsers
```powershell tab=bash-powershell lang=csharp
$env:HEADED="1"
dotnet test
```
To run your test on multiple browsers or configurations, you need to invoke the `dotnet test` command multiple times. There you can then either specify the `BROWSER` environment variable or set the `Playwright.BrowserName` via the runsettings file:
### Run tests on different browsers: Browser env
```bash
dotnet test --settings:chromium.runsettings
dotnet test --settings:firefox.runsettings
dotnet test --settings:webkit.runsettings
```
Specify which browser you would like to run your tests on via the `BROWSER` environment variable.
```xml
<?xml version="1.0" encoding="utf-8"?>
```bash tab=bash-bash lang=csharp
BROWSER=webkit dotnet test
```
```batch tab=bash-batch lang=csharp
set BROWSER=webkit
dotnet test
```
```powershell tab=bash-powershell lang=csharp
$env:BROWSER="webkit"
dotnet test
```
### Run tests on different browsers: launch configuration
Specify which browser you would like to run your tests on by adjusting the launch configuration options:
```bash
dotnet test -- Playwright.BrowserName=webkit
```
To run your test on multiple browsers or configurations, you need to invoke the `dotnet test` command multiple times. There you can then either specify the `BROWSER` environment variable or set the `Playwright.BrowserName` via the runsettings file:
```bash
dotnet test --settings:chromium.runsettings
dotnet test --settings:firefox.runsettings
dotnet test --settings:webkit.runsettings
```
```xml
<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
<Playwright>
<BrowserName>chromium</BrowserName>
</Playwright>
</RunSettings>
```
```
For more information see [selective unit tests](https://docs.microsoft.com/en-us/dotnet/core/testing/selective-unit-tests?pivots=mstest) in the Microsoft docs.
### Run specific tests
To run a single test file, use the filter flag followed by the class name of the test you want to run.
```bash
dotnet test --filter "ExampleTest"
```
To run a set of test files, use the filter flag followed by the class names of the tests you want to run.
```bash
dotnet test --filter "ExampleTest1|ExampleTest2"
```
To run a test with a specific title use the filter flag followed by *Name~* and the title of the test.
```bash
dotnet test --filter "Name~GetStartedLink"
```
### Run tests with multiple workers:
<Tabs
groupId="test-runners"
defaultValue="nunit"
values={[
{label: 'NUnit', value: 'nunit'},
{label: 'MSTest', value: 'mstest'}
]
}>
<TabItem value="nunit">
```bash
dotnet test -- NUnit.NumberOfTestWorkers=5
```
</TabItem>
<TabItem value="mstest">
```bash
dotnet test -- MSTest.Parallelize.Workers=5
```
</TabItem>
</Tabs>
## Debugging Tests
Since Playwright runs in .NET, you can debug it with your debugger of choice in e.g. Visual Studio Code or Visual Studio. Playwright comes with the Playwright Inspector which allows you to step through Playwright API calls, see their debug logs and explore [locators](./locators.md).
@ -76,7 +149,7 @@ $env:PWDEBUG=1
dotnet test
```
<img width="712" alt="Playwright Inspector" src="https://user-images.githubusercontent.com/883973/108614092-8c478a80-73ac-11eb-9597-67dfce110e00.png"></img>
![debugging tests with playwright inspector](https://github.com/microsoft/playwright/assets/13063165/a1e758d3-d379-414f-be0b-7339f12bb635)
Check out our [debugging guide](./debug.md) to learn more about the [Playwright Inspector](./debug.md#playwright-inspector) as well as debugging with [Browser Developer tools](./debug.md#browser-developer-tools).

View file

@ -5,107 +5,18 @@ title: "Test Runners"
## Introduction
While Playwright for .NET isn't tied to a particular test runner or testing framework, in our experience
it works best with the built-in .NET test runner, and using NUnit as the test framework. NUnit is
also what we use internally for [our tests](https://github.com/microsoft/playwright-dotnet/tree/main/src/Playwright.Tests).
While Playwright for .NET isn't tied to a particular test runner or testing framework, in our experience it works best with the built-in .NET test runner, and using NUnit as the test framework. NUnit is also what we use internally for [our tests](https://github.com/microsoft/playwright-dotnet/tree/main/src/Playwright.Tests).
Playwright and Browser instances can be reused between tests for better performance. We
recommend running each test case in a new BrowserContext, this way browser state will be
isolated between the tests.
<!-- TOC -->
## NUnit
Playwright provides base classes to write tests with NUnit via the [`Microsoft.Playwright.NUnit`](https://www.nuget.org/packages/Microsoft.Playwright.NUnit) package.
### Creating an NUnit project
```bash
# Create a new project
dotnet new nunit -n PlaywrightTests
cd PlaywrightTests
# Add the required reference
dotnet add package Microsoft.Playwright.NUnit
dotnet build
# Install the required browsers and operating system dependencies
pwsh bin/Debug/netX/playwright.ps1 install --with-deps
```
Modify the UnitTest1.cs:
```csharp
using Microsoft.Playwright.NUnit;
namespace PlaywrightTests;
[Parallelizable(ParallelScope.Self)]
[TestFixture]
public class MyTest : PageTest
{
[Test]
public async Task ShouldHaveTheCorrectSlogan()
{
await Page.GotoAsync("https://playwright.dev");
await Expect(Page.Locator("text=enables reliable end-to-end testing for modern web apps")).ToBeVisibleAsync();
}
[Test]
public async Task ShouldHaveTheCorrectTitle()
{
await Page.GotoAsync("https://playwright.dev");
var title = Page.Locator(".navbar__inner .navbar__title");
await Expect(title).ToHaveTextAsync("Playwright");
}
}
```
Run your tests against Chromium
```bash
dotnet test
```
Run your tests against WebKit
```bash tab=bash-bash lang=csharp
BROWSER=webkit dotnet test
```
```batch tab=bash-batch lang=csharp
set BROWSER=webkit
dotnet test
```
```powershell tab=bash-powershell lang=csharp
$env:BROWSER="webkit"
dotnet test
```
Run your tests with GUI
```bash tab=bash-bash lang=csharp
HEADED=1 dotnet test
```
```batch tab=bash-batch lang=csharp
set HEADED=1
dotnet test
```
```powershell tab=bash-powershell lang=csharp
$env:HEADED="1"
dotnet test
```
You can also choose specifically which tests to run, using the [filtering capabilities](https://docs.microsoft.com/en-us/dotnet/core/testing/selective-unit-tests?pivots=nunit):
```bash
dotnet test --filter "Name~Slogan"
```
Check out the [installation guide](./intro.md) to get started.
### Running NUnit tests in Parallel
@ -114,6 +25,10 @@ Only `ParallelScope.Self` is supported.
For CPU-bound tests, we recommend using as many workers as there are cores on your system, divided by 2. For IO-bound tests you can use as many workers as you have cores.
```bash
dotnet test -- NUnit.NumberOfTestWorkers=5
```
### Customizing [BrowserContext] options
To customize context options, you can override the `ContextOptions` method of your test class derived from `Microsoft.Playwright.MSTest.PageTest` or `Microsoft.Playwright.MSTest.ContextTest`. See the following example:
@ -223,91 +138,7 @@ There are a few base classes available to you in `Microsoft.Playwright.NUnit` na
Playwright provides base classes to write tests with MSTest via the [`Microsoft.Playwright.MSTest`](https://www.nuget.org/packages/Microsoft.Playwright.MSTest) package.
### Creating an MSTest project
```bash
# Create a new project
dotnet new mstest -n PlaywrightTests
cd PlaywrightTests
# Add the required reference
dotnet add package Microsoft.Playwright.MSTest
dotnet build
# Install the required browsers and operating system dependencies
pwsh bin/Debug/netX/playwright.ps1 install --with-deps
```
Modify the UnitTest1.cs:
```csharp
using Microsoft.Playwright.MSTest;
namespace PlaywrightTests;
[TestClass]
public class UnitTest1: PageTest
{
[TestMethod]
public async Task ShouldHaveTheCorrectSlogan()
{
await Page.GotoAsync("https://playwright.dev");
await Expect(Page.Locator("text=enables reliable end-to-end testing for modern web apps")).ToBeVisibleAsync();
}
[TestMethod]
public async Task ShouldHaveTheCorrectTitle()
{
await Page.GotoAsync("https://playwright.dev");
var title = Page.Locator(".navbar__inner .navbar__title");
await Expect(title).ToHaveTextAsync("Playwright");
}
}
```
Run your tests against Chromium
```bash
dotnet test
```
Run your tests against WebKit
```bash tab=bash-bash lang=csharp
BROWSER=webkit dotnet test
```
```batch tab=bash-batch lang=csharp
set BROWSER=webkit
dotnet test
```
```powershell tab=bash-powershell lang=csharp
$env:BROWSER="webkit"
dotnet test
```
Run your tests with GUI
```bash tab=bash-bash lang=csharp
HEADED=1 dotnet test
```
```batch tab=bash-batch lang=csharp
set HEADED=1
dotnet test
```
```powershell tab=bash-powershell lang=csharp
$env:HEADED="1"
dotnet test
```
You can also choose specifically which tests to run, using the [filtering capabilities](https://docs.microsoft.com/en-us/dotnet/core/testing/selective-unit-tests?pivots=mstest):
```bash
dotnet test --filter "Name~Slogan"
```
Check out the [installation guide](./intro.md) to get started.
### Running MSTest tests in Parallel
@ -331,7 +162,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace PlaywrightTests;
[TestClass]
public class UnitTest1 : PageTest
public class ExampleTest : PageTest
{
[TestMethod]
public async Task TestWithCustomContextOptions()

View file

@ -10,7 +10,6 @@ Playwright Trace Viewer is a GUI tool that lets you explore recorded Playwright
**You will learn**
- How to record a trace
- How to open the HTML report
- How to open the trace viewer
## Recording a trace
@ -124,8 +123,6 @@ public class Tests : PageTest
[TearDown]
public async Task TearDown()
{
// This will produce e.g.:
// bin/Debug/net8.0/playwright-traces/PlaywrightTests.Tests.Test1.zip
await Context.Tracing.StopAsync(new()
{
Path = Path.Combine(
@ -152,17 +149,17 @@ using System.Text.RegularExpressions;
using Microsoft.Playwright;
using Microsoft.Playwright.MSTest;
namespace PlaywrightTestsMSTest;
namespace PlaywrightTests;
[TestClass]
public class UnitTest1 : PageTest
public class ExampleTest : PageTest
{
[TestInitialize]
public async Task TestInitialize()
{
await Context.Tracing.StartAsync(new()
{
Title = TestContext.TestName,
Title = TestContext.CurrentContext.Test.ClassName + "." + TestContext.
Screenshots = true,
Snapshots = true,
Sources = true
@ -172,20 +169,18 @@ public class UnitTest1 : PageTest
[TestCleanup]
public async Task TestCleanup()
{
// This will produce e.g.:
// bin/Debug/net8.0/playwright-traces/PlaywrightTests.UnitTest1.zip
await Context.Tracing.StopAsync(new()
{
Path = Path.Combine(
Environment.CurrentDirectory,
"playwright-traces",
$"{TestContext.FullyQualifiedTestClassName}.zip"
$"{TestContext.CurrentContext.Test.ClassName}.{TestContext.CurrentContext.Test.Name}.zip"
)
});
}
[TestMethod]
public async Task TestYourOnlineShop()
public async Task GetStartedLink()
{
// ...
}
@ -195,11 +190,11 @@ public class UnitTest1 : PageTest
</TabItem>
</Tabs>
This will record the trace and place it into the `bin/Debug/net8.0/playwright-traces/` directory.
This will record a zip file for each test, e.g. `PlaywrightTests.ExampleTest.GetStartedLink.zip` and place it into the `bin/Debug/net8.0/playwright-traces/` directory.
## Opening the trace
You can open the saved trace using the Playwright CLI or in your browser on [`trace.playwright.dev`](https://trace.playwright.dev). Make sure to add the full path to where your `trace.zip` file is located. This should include the `test-results` directory followed by the test name and then `trace.zip`.
You can open the saved trace using the Playwright CLI or in your browser on [`trace.playwright.dev`](https://trace.playwright.dev). Make sure to add the full path to where your trace's zip file is located. Once opened you can click on each action or use the timeline to see the state of the page before and after each action. You can also inspect the log, source and network during each step of the test. The trace viewer creates a DOM snapshot so you can fully interact with it, open devtools etc.
```bash java
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="show-trace trace.zip"
@ -210,14 +205,19 @@ playwright show-trace trace.zip
```
```bash csharp
pwsh bin/Debug/netX/playwright.ps1 show-trace trace.zip
pwsh bin/Debug/net8.0/playwright.ps1 show-trace bin/Debug/net8.0/playwright-traces/PlaywrightTests.ExampleTest.GetStartedLink.zip
```
## Viewing the trace
View traces of your test by clicking through each action or hovering using the timeline and see the state of the page before and after the action. Inspect the log, source and network during each step of the test. The trace viewer creates a DOM snapshot so you can fully interact with it, open devtools etc.
######
* langs: python, java
![playwright trace viewer](https://github.com/microsoft/playwright/assets/13063165/10fe3585-8401-4051-b1c2-b2e92ac4c274)
######
* langs: csharp
![playwright trace viewer dotnet](https://github.com/microsoft/playwright/assets/13063165/4372d661-5bfa-4e1f-be65-0d2fe165a75c)
To learn more check out our detailed guide on [Trace Viewer](/trace-viewer.md).
## What's next

View file

@ -5,9 +5,33 @@ title: "Writing tests"
## Introduction
Playwright assertions are created specifically for the dynamic web. Checks are automatically retried until the necessary conditions are met. Playwright comes with [auto-wait](./actionability.md) built in meaning it waits for elements to be actionable prior to performing actions. Playwright provides the [Expect](./test-assertions) function to write assertions.
Playwright tests are simple, they
Take a look at the example test below to see how to write a test using using [locators](/locators.md) and web first assertions.
- **perform actions**, and
- **assert the state** against expectations.
There is no need to wait for anything prior to performing an action: Playwright
automatically waits for the wide range of [actionability](./actionability.md)
checks to pass prior to performing each action.
There is also no need to deal with the race conditions when performing the checks -
Playwright assertions are designed in a way that they describe the expectations
that need to be eventually met.
That's it! These design choices allow Playwright users to forget about flaky
timeouts and racy checks in their tests altogether.
**You will learn**
- [How to write the first test](/writing-tests.md#first-test)
- [How to perform actions](/writing-tests.md#actions)
- [How to use assertions](/writing-tests.md#assertions)
- [How tests run in isolation](/writing-tests.md#test-isolation)
- [How to use test hooks](/writing-tests.md#using-test-hooks)
## First test
Take a look at the following example to see how to write a test.
<Tabs
groupId="test-runners"
@ -30,30 +54,28 @@ namespace PlaywrightTests;
[Parallelizable(ParallelScope.Self)]
[TestFixture]
public class Tests : PageTest
public class ExampleTest : PageTest
{
[Test]
public async Task HomepageHasPlaywrightInTitleAndGetStartedLinkLinkingtoTheIntroPage()
public async Task HasTitle()
{
await Page.GotoAsync("https://playwright.dev");
// Expect a title "to contain" a substring.
await Expect(Page).ToHaveTitleAsync(new Regex("Playwright"));
}
// create a locator
var getStarted = Page.GetByRole(AriaRole.Link, new() { Name = "Get started" });
// Expect an attribute "to be strictly equal" to the value.
await Expect(getStarted).ToHaveAttributeAsync("href", "/docs/intro");
[Test]
public async Task GetStartedLink()
{
await Page.GotoAsync("https://playwright.dev");
// Click the get started link.
await getStarted.ClickAsync();
await Page.GetByRole(AriaRole.Link, new() { Name = "Get started" }).ClickAsync();
// Expects page to have a heading with the name of Installation.
await Expect(Page
.GetByRole(AriaRole.Heading, new() { Name = "Installation" }))
.ToBeVisibleAsync();
}
await Expect(Page.GetByRole(AriaRole.Heading, new() { Name = "Installation" })).ToBeVisibleAsync();
}
}
```
@ -70,55 +92,109 @@ using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace PlaywrightTests;
[TestClass]
public class UnitTest1 : PageTest
public class ExampleTest : PageTest
{
[TestMethod]
public async Task HomepageHasPlaywrightInTitleAndGetStartedLinkLinkingtoTheIntroPage()
public async Task HasTitle()
{
await Page.GotoAsync("https://playwright.dev");
// Expect a title "to contain" a substring.
await Expect(Page).ToHaveTitleAsync(new Regex("Playwright"));
}
// create a locator
var getStarted = Page.GetByRole(AriaRole.Link, new() { Name = "Get started" });
// Expect an attribute "to be strictly equal" to the value.
await Expect(getStarted).ToHaveAttributeAsync("href", "/docs/intro");
[TestMethod]
public async Task GetStartedLink()
{
await Page.GotoAsync("https://playwright.dev");
// Click the get started link.
await getStarted.ClickAsync();
await Page.GetByRole(AriaRole.Link, new() { Name = "Get started" }).ClickAsync();
// Expects the URL to contain intro.
await Expect(Page).ToHaveURLAsync(new Regex(".*intro"));
}
// Expects page to have a heading with the name of Installation.
await Expect(Page.GetByRole(AriaRole.Heading, new() { Name = "Installation" })).ToBeVisibleAsync();
}
}
```
</TabItem>
</Tabs>
### Assertions
## Actions
### Navigation
Most of the tests will start by navigating the page to a URL. After that, the test
will be able to interact with the page elements.
```csharp
await Page.GotoAsync("https://playwright.dev");
```
Playwright will wait for the page to reach the load state prior to moving forward.
Learn more about the [`method: Page.goto`] options.
### Interactions
Performing actions starts with locating the elements. Playwright uses [Locators API](./locators.md) for that. Locators represent a way to find element(s) on the page at any moment, learn more about the [different types](./locators.md) of locators available. Playwright will wait for the element to be [actionable](./actionability.md) prior to performing the action, so there is no need to wait for it to become available.
```csharp
// Create a locator.
var getStarted = Page.GetByRole(AriaRole.Link, new() { Name = "Get started" });
// Click it.
await getStarted.ClickAsync();
```
In most cases, it'll be written in one line:
```csharp
await Page.GetByRole(AriaRole.Link, new() { Name = "Get started" }).ClickAsync();
```
### Basic actions
This is the list of the most popular Playwright actions. Note that there are many more, so make sure to check the [Locator API](./api/class-locator.md) section to
learn more about them.
| Action | Description |
| :- | :- |
| [`method: Locator.check`] | Check the input checkbox |
| [`method: Locator.click`] | Click the element |
| [`method: Locator.uncheck`] | Uncheck the input checkbox |
| [`method: Locator.hover`] | Hover mouse over the element |
| [`method: Locator.fill`] | Fill the form field, input text |
| [`method: Locator.focus`] | Focus the element |
| [`method: Locator.press`] | Press single key |
| [`method: Locator.setInputFiles`] | Pick files to upload |
| [`method: Locator.selectOption`] | Select option in the drop down |
## Assertions
Playwright provides an async function called [Expect](./test-assertions) to assert and wait until the expected condition is met.
```csharp
await Expect(Page).ToHaveTitleAsync(new Regex("Playwright"));
```
```
Here is the list of the most popular async assertions. Note that there are [many more](./test-assertions.md) to get familiar with:
| Assertion | Description |
| :- | :- |
| [`method: LocatorAssertions.toBeChecked`] | Checkbox is checked |
| [`method: LocatorAssertions.toBeEnabled`] | Control is enabled |
| [`method: LocatorAssertions.toBeVisible`] | Element is visible |
| [`method: LocatorAssertions.toContainText`] | Element contains text |
| [`method: LocatorAssertions.toHaveAttribute`] | Element has attribute |
| [`method: LocatorAssertions.toHaveCount`] | List of elements has given length |
| [`method: LocatorAssertions.toHaveText`] | Element matches text |
| [`method: LocatorAssertions.toHaveValue`] | Input element has value |
| [`method: PageAssertions.toHaveTitle`] | Page has title |
| [`method: PageAssertions.toHaveURL`] | Page has URL |
### Locators
[Locators](./locators.md) are the central piece of Playwright's auto-waiting and retry-ability. Locators represent a way to find element(s) on the page at any moment and are used to perform actions on elements such as `.ClickAsync` `.FillAsync` etc.
```csharp
var getStarted = Page.GetByRole(AriaRole.Link, new() { Name = "Get started" });
await Expect(getStarted).ToHaveAttributeAsync("href", "/docs/installation");
await getStarted.ClickAsync();
```
### Test Isolation
## Test Isolation
The Playwright NUnit and MSTest test framework base classes will isolate each test from each other by providing a separate `Page` instance. Pages are isolated between tests due to the Browser Context, which is equivalent to a brand new browser profile, where every test gets a fresh environment, even when multiple tests run in a single Browser.
@ -141,7 +217,7 @@ namespace PlaywrightTests;
[Parallelizable(ParallelScope.Self)]
[TestFixture]
public class Tests : PageTest
public class ExampleTest : PageTest
{
[Test]
public async Task BasicTest()
@ -162,7 +238,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace PlaywrightTests;
[TestClass]
public class UnitTest1 : PageTest
public class ExampleTest : PageTest
{
[TestMethod]
public async Task BasicTest()
@ -175,7 +251,7 @@ public class UnitTest1 : PageTest
</TabItem>
</Tabs>
### Using Test Hooks
## Using Test Hooks
You can use `SetUp`/`TearDown` in NUnit or `TestInitialize`/`TestCleanup` in MSTest to prepare and clean up your test environment:
@ -198,7 +274,7 @@ namespace PlaywrightTests;
[Parallelizable(ParallelScope.Self)]
[TestFixture]
public class Tests : PageTest
public class ExampleTest : PageTest
{
[Test]
public async Task MainNavigation()
@ -226,7 +302,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace PlaywrightTests;
[TestClass]
public class UnitTest1 : PageTest
public class ExampleTest : PageTest
{
[TestMethod]
public async Task MainNavigation()
@ -251,3 +327,5 @@ public class UnitTest1 : PageTest
- [Run single test, multiple tests, headed mode](./running-tests.md)
- [Generate tests with Codegen](./codegen.md)
- [See a trace of your tests](./trace-viewer-intro.md)
- [Run tests on CI](./ci-intro.md)
- [Learn more about the NUnit and MSTest base classes](./test-runners.md)