mu88
mu88

Reputation: 5404

Execute Playwright not via test runner

I've written a Playwright test but instead of running it via the test runner (NUnit), I'd like to run my Playwright code either from a console application or an ASP.NET Core background service.

What is the easiest way to setup Playwright so that it can be run without a test runner?

This is my current console app code:

using Microsoft.Playwright;

var browserTest = new Microsoft.Playwright.NUnit.BrowserTest();
var context = await browserTest.NewContext();
var page = await context.NewPageAsync();
await page.SetViewportSizeAsync(600,800);
await page.GotoAsync("https://www.google.com/");

...raising a NullReferenceException for await browserTest.NewContext();.

I'm using:

Upvotes: 3

Views: 2658

Answers (2)

PandaMagnus
PandaMagnus

Reputation: 281

The second way @mu88 posted is the most correct in this case. No reason to bring in NUnit dependencies for a console app. However, I'd recommend adding a line before creating a new page:

IBrowserContext context = await chrome.NewContextAsync();

This gives you control over the specific context created. Calling browser.NewPageAsync() hides some stuff that might be necessary. The total code block would look like:

using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync();
IBrowserContext context = await chrome.NewContextAsync();
var page = await browser.NewPageAsync();

Upvotes: 2

mu88
mu88

Reputation: 5404

The console app has to reference the NuGet package Microsoft.Playwright.NUnit and must run the following startup code:

var pageTest = new PageTest();
pageTest.WorkerSetup();
await pageTest.PlaywrightSetup();
await pageTest.BrowserSetup();
await pageTest.ContextSetup();
await pageTest.PageSetup();
var page = pageTest.Page;

Then you can do the regular Playwright stuff:

await page.SetViewportSizeAsync(600, 800);
await page.GotoAsync("https://www.google.com/");

Even easier, as @max-schmitt pointed out via the official docs: reference the NuGet package Microsoft.Playwright and instantiate Playwright like this:

using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync();
var page = await browser.NewPageAsync();

Upvotes: 3

Related Questions