Playwright has a great trace viewer that allows us to see exactly what is happening in our tests. This is especially helpful when something goes wrong. Let’s take a look at how we activate tracing and access the information it collects.
Activate tracing
We need a bit of code that runs before and after our tests. The SetUp and TearDown methods of NUnit are the perfect place to put them. However, we need a way to tell those methods which tests to trace, otherwise every test collects tracing info. The simplest way I found is to use a test category, like TraceIt, that we put on the tests we are interested in:
1 |
[Category("TraceIt")] |
We can then check for this attribute in the SetUp and TearDown methods and only create the tracing data if the attribute is present:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
[SetUp] public async Task SetUp() { var properties = TestContext.CurrentContext.Test.Properties; if (properties.ContainsKey("Category") && (string)properties.Get("Category")! == "TraceIt") { await Context.Tracing.StartAsync( new TracingStartOptions { Screenshots = true, Snapshots = true, Sources = true, Name = TestContext.CurrentContext.Test.FullName }); } } [TearDown] public async Task TearDown() { var properties = TestContext.CurrentContext.Test.Properties; if (properties.ContainsKey("Category") && (string)properties.Get("Category")! == "TraceIt") { await Context.Tracing.StopAsync( new TracingStopOptions { Path = TestContext.CurrentContext.Test.FullName + ".zip" }); } } |
Collect the tracing data
With our methods in place, we can add the test category to the tests we want to trace and run NUnit. At the end we should find a *.zip file with the test name in the output directory:
Open the trace file
We can go to the output directory and run playwright.ps1 with the option show-trace and the *.zip file we are interested in:
1 |
.\playwright.ps1 show-trace .\PlaywrightDemo.TraceTest.MissingText.zip |
If Playwright complains that the *.zip
file does not exist, omit it from the command and pick it in the trace viewer manually:
Inspect the trace
The trace viewer shows us the browser through the whole test. We have snapshots of the DOM at all times and can interact with the site as if we had it open in the developer tools of a regular browser:
I find this one of the greatest improvements over the tooling we had so far for end-to-end tests. It makes everything so much simpler to debug, then everything the browser interacted with is here.
Next
Should your tests stop working, use the trace viewer to figure out what is going on. But something that is still not enough. Next week we take screenshots and record videos of our tests.