CrispinH
CrispinH

Reputation: 2059

How to record a trace in Playwright with .NET?

I'm starting out with using Playwright to test a Blazor application. It seems that the test project has to be running before testing starts so I've put the test project in a separate solution. So far I have successfully used the codegen facility to run tests but now I'd like to run a trace.

For context, I'm using .NET 7 for the Blazor and test projects and I've got the Nuget package Microsoft.Playwright.MSTest v1.33.0 installed in the test project. Usually I use xUnit, but apparently MSTest or NUnit are preferred for Playwright.

I went to the dotnet documentation where it shows an example and I put this in a test method.

    private readonly IPlaywright _playwright;

    [TestMethod]
    public async Task RecordingATrace()
        {
        using var browser = _playwright.Chromium.LaunchAsync();
        using var context = await browser.NewContextAsync();

        // Start tracing before creating / navigating a page.
        await context.Tracing.StartAsync(new()
            {
            Screenshots = true,
            Snapshots = true,
            Sources = true
            });

        var page = context.NewPageAsync();
        await page.GotoAsync("https://playwright.dev");

        // Stop tracing and export it into a zip archive.
        await context.Tracing.StopAsync(new()
            {
            Path = "trace.zip"
            });
        }

In the documentation, the first couple of lines are shown as:

await using var browser = playwright.Chromium.LaunchAsync();
await using var context = await browser.NewContextAsync();

and Visual Studio complained about that (and it seems wrong to me anyway), so I removed the 'await' directives.

Then it appears that NewContextAsync doesn't exist and Intellisense isn't prompting with something that might work.

So how to I run a trace with Playwright? I'm happy to use the command line instead but I've yet to find any documentation on that.

Upvotes: 1

Views: 1569

Answers (1)

CrispinH
CrispinH

Reputation: 2059

It turned out that there was too much code in the documentation. This simplified version worked for me:

    [TestMethod]
    public async Task MyTest()
        {    
        await Context.Tracing.StartAsync(new()    // TracingStartOptions
            {
            Screenshots = true,
            Snapshots = true,
            Sources = true,
            });

       await Page.GotoAsync("...

       // Rest of the test body

        await Context.Tracing.StopAsync(new()
            {
            Path = "trace.zip"
            });
         }

The trace ends up in the following the .\bin\Debug\net7.0 folder. To view the trace, open a Terminal window in Visual Studio 2022 (or PowerShell in the project folder I guess) and execute the following:

.\bin\Debug\net7.0\playwright.ps1 show-trace .\bin\Debug\net7.0\trace.zip

Upvotes: 2

Related Questions