Web applications
editWebAppBrowser opens the pages of a web application. With the application in memory (a TestServer), a test runs the whole stack in one process: the server, the HTML, the CSS, the scripts of the pages and the user input. It works with any ASP.NET Core application: MVC, Razor Pages, Blazor, minimal APIs, or your own middleware.
// The application runs in memory: Program is the entry point of the application under test
await using var factory = new WebApplicationFactory<Program>();
await using var browser = WebAppBrowser.Create(factory.Server);
var page = await browser.OpenAsync("/");
await Expect(page).ToHaveTitleAsync("Home");
// Follow a link, fill a form and submit it: the POST, the redirect and the cookie go through the application
await page.GetByRole("link", "Sign in").ClickAsync();
await page.GetByLabel("Name").FillAsync("Ada");
await page.GetByRole("button", "Sign in").ClickAsync();
await Expect(page).ToHaveUrlAsync("/profile");
await Expect(page.Locator("#greeting")).ToHaveTextAsync("Hello Ada");Connect the browser
| Method | Application |
|---|---|
WebAppBrowser.Create(server) | An application in memory: WebApplicationFactory<Program>.Server (package Microsoft.AspNetCore.Mvc.Testing), or app.GetTestServer() after UseTestServer() |
WebAppBrowser.Create(uri) | A server on the network (Kestrel, a development server...) |
new WebAppBrowser(baseAddress, loader) | Any DocumentLoader, for instance one of TestDocumentLoaders |
The pages handle the cookies and the redirects, as a browser does: the pages of a WebAppBrowser share their cookies (Cookies), and two browsers are two users.
Replace the services of the application
Configure the application as in any integration test of ASP.NET Core, then open its pages:
await using var application = new WebApplicationFactory<Program>();
await using var factory = application.WithWebHostBuilder(builder =>
builder.ConfigureTestServices(services => services.AddSingleton<GreetingService, FrenchGreetingService>()));
await using var browser = WebAppBrowser.Create(factory.Server);
// Sign in by setting the cookie of the application
browser.Cookies.SetCookie("http://localhost/", "user=Ada");
var page = await browser.OpenAsync("/profile");
Assert.Equal("Bonjour Ada", page.Find("#greeting").TextContent);Pages
BrowserPage navigates (GoToAsync, GoBackAsync, GoForwardAsync, ReloadAsync) and waits until the new document is loaded. The queries, the actions, the waits and the snapshots are the ones of TestPage, shared with the tests of Blazor components: see Locators and assertions, User input and Snapshots.
The pages run their scripts; set EnableJavaScript to false to test the pages as without JavaScript. The errors of the scripts are in ScriptErrors, their console in ConsoleMessages, and the violations of the content security policies (including the ones raised while the document loads) in ContentSecurityPolicyViolations: what the developer tools of a browser report.
Browsing context options
ConfigureBrowsingContext changes any option of the browsing contexts of the pages (BrowsingContextOptions): the user agent, the languages, the permissions, the geolocation, the dialogs... It receives the options made from the other settings and returns the options to use, usually with a with expression. The pages still record their console messages, script errors and content security policy violations, and call the callbacks that the function sets. The function cannot replace the document loader nor the script engine, which the pages depend on to wait and to run the JavaScript interop: use the loader of the browser and EnableJavaScript instead.
var reports = new List<ContentSecurityPolicyViolationReport>();
await using var factory = new WebApplicationFactory<Program>();
await using var browser = WebAppBrowser.Create(factory.Server, new WebAppBrowserOptions
{
// Change any option of the browsing contexts of the pages
ConfigureBrowsingContext = options => options with
{
UserAgent = "TestBrowser/1.0",
ContentSecurityPolicyViolation = (_, report) => reports.Add(report),
},
});
var page = await browser.OpenAsync("/secure");
Assert.Equal("TestBrowser/1.0", page.BrowsingContext.Window.Navigator.UserAgent);
// The page still records what it reports, and calls the callbacks of the options
Assert.Single(page.ContentSecurityPolicyViolations);
Assert.Single(reports);ComponentTestHostOptions has the same function for the page that hosts the components.
Clipboard
Each page has a clipboard of its own, so tests that run in parallel do not see what the others copy. FakeClipboard supplies what the pages paste (ProvideContent) and receives what they copy (ContentChanged). Set it with ConfigureBrowsingContext: the pages that use the same instance share it. Without ProvideContent, the pages read what was last written.
var copied = new List<string?>();
var clipboard = new FakeClipboard
{
// What the pages paste or read
ProvideContent = () => [FakeClipboard.CreateTextItem("Pasted text")],
// Called with what the pages copy or write
ContentChanged = items => copied.Add(FakeClipboard.GetText(items)),
};
await using var factory = new WebApplicationFactory<Program>();
await using var browser = WebAppBrowser.Create(factory.Server, new WebAppBrowserOptions
{
// The pages that use the same clipboard share it
ConfigureBrowsingContext = options => options with { Clipboard = clipboard },
});
var page = await browser.OpenAsync("/secure");
await page.Find("#copy").ClickAsync();
await page.Find("#paste").ClickAsync();
Assert.Equal(["Copied text"], copied);
Assert.Equal("Pasted text", page.Find("output").TextContent);When the content returned by ProvideContent changes, as when another application writes to the clipboard, NotifyContentChanged fires the clipboardchange events of the pages.
Waiting
Each action waits until the page is idle: no task in its event loop, and no request in progress. Some requests never end while a page is open: the server-sent events and the long polling of SignalR do not count (IsLongLivedRequest). When the result depends on a message the server pushes later (SignalR, Blazor Server), wait for it with an assertion of Expect, which retries until it passes.