NE.Standard

Testing an application

A page's whole contract lives on the server: the view's bindings and rules, its filters, the route's authorization, the controller's commands. NE.Standard.UI.Testing checks that contract where it lives. A test boots the application's own startup with no platform under it, opens a page through the host's real path, acts on its components the way a reader does and reads what the page received — no browser, no web host.

dotnet add package NE.Standard.UI.Testing

The package depends on the engine and the platform-free C# client runtime, and on no test framework or assertion library: a page answers with plain values, and a misuse — a component that is not there, a press on a button a reader could not press — throws InvalidOperationException. The examples below use xUnit.

A first test

public sealed class SignUpScreenTests
{
    [Fact]
    public async Task AnInvalidEmailShowsTheRuleAndTheSubmitIsRefused()
    {
        await using UITestApp app = UITestApp.Create<AppStartup>();
        UITestPage page = await app.OpenAsync("/screens/sign-up");
        UITestComponent email = page.ComponentBoundTo(nameof(SignUpController.Email));

        await email.SetValueAsync("not-an-email");
        UITestCommandResult submit = await page.ComponentNamed("Create account").ClickAsync();

        Assert.Equal("That does not look like an email address.", email.ValidationMessage);
        Assert.False(submit.Sent);
    }
}

The email's rule runs in the browser, so no command reaches the server and a controller-only test would never see it. Here the page evaluates the field's rules as the client does, and the submit is refused while its form has a field in error, as the browser refuses it.

The application

UITestApp.Create<TStartup>() builds the application from its UIStartupBase the way its host does — the routes, the services, each opened route's view compiled as it is reached — and puts a test client where the platform would be: what the runtimes push, the dialogs they open and the files they send reach the page they are addressed to. Two optional arguments shape it:

await using UITestApp app = UITestApp.Create<AppStartup>(
    configureServices: services => services.AddSingleton<IClock>(new FixedClock(Today)),
    configureApplication: application => application.ConfigureSessions(sessions => sessions.IdleTimeout = TimeSpan.FromMinutes(5))
);

configureServices runs after the startup's own registrations, so a fake registered there replaces the real service. UITestApp registers a default /_ne/content IUIContentAddressResolver out of the box, which configureServices may replace.

The scheduler is parked. A runtime answers a command with what it changed for the page that asked and keeps the rest — a posted action's writes, OnAttachedAsync's, what another page's command changed — for the scheduled flush. In a test nothing flushes on its own — but an effect pushed outside a command, which goes out behind what the state holds: page.FlushAsync() delivers it to every page attached, so what a command answered and what waits for the flush are told apart without timing.

Opening a page

app.OpenAsync(address, session) resolves the address as a page load does — the view filters, the route's authorization, a refusal sent to sign in or to the forbidden page — attaches a runtime and starts the page from the snapshot a connecting page is sent. A page whose view binds what names nothing — a property the controller lacks, a step the server cannot read — is refused, naming each binding, since the server only logs it; advice (an argument no parameter takes, a Root binding a row's item shadows) is logged, not refused. app.AllowsCompileWarnings = true opens such a page anyway, and page.CompileWarnings lists every warning with its Kind. page.Route is the route that answered:

UITestPage refused = await app.OpenAsync("/screens/admin");

Assert.Equal("/screens/sign-in", refused.Route);
Assert.Equal("/screens/sign-in?returnUrl=%2Fscreens%2Fadmin", refused.Address);

UITestPage admin = await app.OpenAsync("/screens/admin", session => session.SignIn("robin", roles: ["admin"]));

Assert.Equal("/screens/admin", admin.Route);

The session is described, then stored in the application's own session store and presented as a browser presents its cookie, so the resolver, the authorization and the filters read it as they read a real one: SignIn(userId, roles, permissions), InLanguage("ru"), InTimeZone("Europe/Berlin"), WithNotificationPermission(UINotificationPermission.Granted). Under claims as the identity source the same user travels as the host's principal, and page.Session (UITestSession) reads the session's live state after sign-in, sign-out, language, time-zone or permission updates. Without a description a page opens as an anonymous first visit. page.OpenAsync(address) opens another page in the same session — following a NavigateEffect, or a second tab. page.CloseAsync() closes a page as a reader closing its tab does — its connection leaves the runtime through the host and it hears nothing more — and returns once the controller's OnDetachedAsync has run. The runtime stays for its retention, as a closed tab's does, and a background command the page raised runs on until that stay ends.

An address may carry a query, read as the route's parameters as the host reads them — + a space, a key given twice a list: app.OpenAsync("/screens/catalogue?role=db").

Finding a component

Call Finds
page.Component(id) the component with that id in the view
page.ComponentBoundTo(path), page.ComponentBoundTo<TSource>(c => ...) the one component whose value, collection or other property is bound to the controller path (and on a UITestComponent, within its subtree)
page.ComponentNamed(name) the one component a reader knows by that name: its title, accessible name or tooltip, as written or as shown
component.Rows, component.Row(key) a list's visible rows (after any plain-host FilterBy, SortBy and Query rules), or a windowed host's realized window rows; on a menu, Row(key) reaches a unique sub-entry too
row.Rows, row.Row(key) a menu row's sub-entries, in the order the server sent them
row.Component(id), row.ComponentBoundTo("Text"), row.ComponentBoundTo<TItem>(x => ...) a component in the row; a path is the item's
row.ContextMenu, component.ContextMenu what a right click shows
component.Menu the menu a split button drops; its rows are the entries

Several components matching is an error that names them: find one by its id instead.

Reading what it shows

A component's state is read off the change sets the page received, applied the way the client applies them: Value, Title, Get(property) and Text(property) (the words in the page's language), IsVisible and IsEnabled (an ancestor collapsed, disabled or loading counts, and so does a dialog that is not open), and ValidationMessage — the strongest of the field's failing rules once the reader has been in it (a rule against another field judged again as that field is written), a value past its bounds, a message routed through ValidationInto, the controller's bound message and the server's refusal. A row's binding is read off the row's item, and a reset with its inserts keeps what the page held under the rows it resends unchanged. The interactions the view declares run as in the browser: a part shown while a switch is on appears when the switch is written.

The page keeps the rest of what it received: page.Effects and page.EffectsOf<ShowNotificationEffect>() (page.ClearEffects() clears the recorded list), the dialogs those effects opened, a press's own included (page.IsDialogOpen(key); a key the view does not declare is refused) — the viewer's close (an × with RaisesClose) letting the edit of a form under the dialog's key go and raising its OnClose, and page.DismissDialogAsync(key) closing one as Escape or a press beside it does, the edit going with it — the visibility a show, hide or collapse wrote, a language or theme the page switched to (stored in the session, its controller told: page.Language), the address an address effect wrote (page.Address), the files sent to it (page.Downloads, cleared by page.ClearDownloads()), and page.Words(value) for an effect's words. page.Controller<T>() is the controller, for what the screen does not show.

Acting on it

Every act goes through the host's own entry points — those the web hub calls — so the value gates and bounds, the command filters and authorization, the exclusive lock all run:

  • SetValueAsync(value) types into a field and leaves it: its change rules and the interactions reading it run, the value is written to the server (or held for its form under an OnSubmit binding, a push waiting behind the edit until a DiscardFormEffect), then its change command, then its blur rules. A number or a date past its Min or Max stays in the field, refused in words, and is not sent; a value no reader could give — a slider past its bounds, a negative number where none is taken — throws. It answers a UITestCommandResult: refused for a value the page or the server refused, else what the change command did.
  • ClickAsync() presses a component. A button that submits a form runs the form's submit rules first and is refused while a field is in error. A surface or a file tile whose Clickable is false throws, as the browser lets its click go by.
  • RenameAsync(title) on a UITestComponent or UITestRow writes the new caption through RenamedTitle and runs any OnRename / OnItemRename command, respecting Renamable, CanRename and one-shot RenameItemEffect grants.
  • DispatchAsync(eventName, eventKeys) raises any event the component declares; eventKeys are the keys the event itself names after its row's, such as a moved row's place. An event that submits its field's form — a code field's save — sends the form's held values first, as a submit button does.
  • row.ClickAsync() presses a row; row.ChooseAsync() writes the list's chosen key where it binds one, then presses.
  • component.RequestItemWindowAsync(anchor, count, mode) asks a windowed UIItemSourceBase host for a window of rows in Replace or Extend mode.
  • page.SetResponsiveTier(tier) and page.SetViewportWidth(widthPixels) set page.ResponsiveTier (Xxl by default) so IsVisible, IsEnabled and Get<T>(property) resolve UIResponsive<T> values at that breakpoint.
  • page.GoBackAsync() and page.GoForwardAsync() step through the in-place address history written by PushAddressEffect, ReplaceAddressEffect and NavigateBackEffect (page.CanGoBack, page.CanGoForward).
  • page.Store (UIClientStore) reads, writes and removes component preferences keyed by authored id and slot.
  • page.PressNotificationActionAsync(toast) presses a toast's action through the command path, once.
  • page.HideAsync() / ShowAsync() take the page off screen and back, as another tab chosen does (HasVisibleViewers), and return once the controller's OnVisibilityChangedAsync has run; ReportNotificationPermissionAsync(...) reports the browser's answer to the permission prompt and returns once OnNotificationPermissionChangedAsync has run.

Each but the three reports (HideAsync, ShowAsync, ReportNotificationPermissionAsync, which return a plain Task) answers with a UITestCommandResult: Sent (whether a command reached the server), Succeeded, Error, and the Effects the page received while it ran. A row deleted with an undo, end to end:

UITestPage chat = await app.OpenAsync("/screens/chat");
UITestComponent conversation = chat.Component(ChatController.ConversationId);
UITestRow last = conversation.Rows[^1];

UITestCommandResult delete = await last.ContextMenu.Row("delete").ClickAsync();
ShowNotificationEffect toast = Assert.Single(delete.Effects.OfType<ShowNotificationEffect>());

Assert.DoesNotContain(conversation.Rows, row => row.Key == last.Key);
Assert.Equal("Undo", chat.Words(toast.Action?.Title));

await chat.PressNotificationActionAsync(toast);

Assert.Equal(last.Key, conversation.Rows[^1].Key);

What it does not model

Layout and styling; popups other than dialogs — a context menu and a flyout stand open; the trimming and debouncing a field does in the browser; what the web hub adds of its own, its call budget and a large value staged beside it. A row's item is the server's own object, so a property the server changed shows on it before the runtime's flush sends the change. Focus, the keyboard and the DOM are the browser's: a test of those drives a browser.