writingTests - CoasterFan5/Blazor-Playwright GitHub Wiki

Writing Tests

Tests go in the shiney new Project.Tests project we made earlier, and will look very similar to the following:

using System.Text.RegularExpressions;
using Microsoft.Playwright;
using Microsoft.Playwright.Xunit;

namespace PlaywrightTests;

public class UnitTest1: PageTest
{
    [Fact]
    public async Task HasTitle()
    {
        await Page.GotoAsync("https://playwright.dev");

        // Expect a title "to contain" a substring.
        await Expect(Page).ToHaveTitleAsync(new Regex("Playwright"));
    }
}

Together, we will write a test as well that checks if the a Blazor page has a body. To start, add all the using statements you will need, declare the namespace, come up with a clever classname.

using Microsoft.Playwright.Xunit;
using System.Threading.Tasks;

namespace App.Tests; // will vary depending on project name

// Name does not matter here
// Notice how we extend PageTest, which is different than a normal bUnit or xUnit test.
public class ReallyGoodTest() : PageTest
{
    [Fact] // declares a method as a test
    //Another name that does not matter
    public async Task PageHasBody() {}
}

We can also add the actual test code:

public void PageHasBody()
    {
        await Page.GotoAsync("http://localhost:5155"); // We are going to address this
        await Expect(Page.Locator("body")).ToBeAttachedAsync();
    }

All in we get the following:

using Microsoft.Playwright.Xunit;
using System.Threading.Tasks;

namespace App.Tests;

public class ReallyGoodTest() : PageTest
{
    [Fact]
    public async Task PageHasBody()
    {
        await Page.GotoAsync("http://localhost:5155");
        await Expect(Page.Locator("body")).ToBeAttachedAsync();
    }
}

When navigating to a page, we use http://localhost:5155 since that is the default port that a new blazor app will run on. If your app is running on a different port, change this url to match. This means also that before we can run our test, we need to have an instance of our app running. Playwright works by opening a browser and simulating user events, and therefore needs a full instance of the app running to properly run it's tests.

dotnet run --project ./src/<ProjectName> # if you are a unix user you can add & at the end of the command to run it as a background task, Windows users, just open a second terminal.

Once this test is written and our app started, we can navigate to our root directory and run the test command.

dotnet test