Testing with Ducky.Testing
Ducky.Testing runs your slices and effects on a real store, with a fake clock, and works with any test framework: a failed check throws DuckyAssertionException.
dotnet add package Ducky.TestingSlices
SliceTest seeds a state, dispatches actions and checks the result:
[Fact]
public void ThemeChanged_NewTheme_Applied() =>
SliceTest.For<SettingsSlice, Settings>()
.Given(new Settings("light", FontSize: 14))
.When(new ThemeChanged("dark"))
.Then(new Settings("dark", FontSize: 14));
[Fact]
public void ThemeChanged_SameTheme_Unchanged() =>
SliceTest.For<SettingsSlice, Settings>()
.Given(new Settings("dark", FontSize: 14))
.When(new ThemeChanged("dark"))
.ThenUnchanged();Then(expected) compares with Equals, Then(state => ...) runs your own assertions, and ThenUnchanged() checks that the reducers returned the same reference.
Effects
EffectTest.Run builds a store with the effect, dispatches one action, waits until the store is idle and returns what the effect dispatched. Given these actions and this effect:
public sealed record Profile(int Id, string Name);
public sealed record LoadProfile(int Id);
public sealed record ProfileLoaded(Profile Profile);
public interface IProfileApi
{
Task<Profile> GetAsync(int id, CancellationToken cancellationToken);
}public sealed class LoadProfileEffect(IProfileApi api) : Effect<LoadProfile>
{
public override async Task Handle(LoadProfile action, EffectContext context, CancellationToken cancellationToken) =>
context.Dispatch(new ProfileLoaded(await api.GetAsync(action.Id, cancellationToken)));
}the test registers a fake for its dependency (this sample nests the effect in a class named App):
[Fact]
public async Task LoadProfile_ApiAnswers_DispatchesProfileLoaded()
{
var run = await EffectTest.Run<App.LoadProfileEffect, LoadProfile>(
new LoadProfile(42),
services: services => services.AddSingleton<IProfileApi>(new StubProfileApi(new Profile(0, "Ada"))));
run.Dispatched.ShouldBe([new ProfileLoaded(new Profile(42, "Ada"))]);
run.Failures.ShouldBeEmpty();
}The actions an effect dispatches usually have no reducer in the test; they are results, not failures. Add the slices the effect reads with configure (d => d.AddSlice<TodosSlice>()) and seed them with arrange (store => store.Seed(...)). The store builds the effect, so an effect that injects a SliceStore gets the store-owned instance.
The whole store
TestStore is an IStore for tests. A test of one slice needs no lambda:
[Fact]
public async Task TestStore_SingleSlice_Create()
{
await using var store = TestStore.Create<TodosSlice>();
store.State.Get<Todos>().Items.Count.ShouldBe(0);
}Several slices, seeding and settling go through Create(configure):
[Fact]
public async Task TestStore_SeedDispatchSettle()
{
await using var store = TestStore.Create(ducky => ducky.AddSlice<TodosSlice>().AddSlice<CartStore>());
store.Seed(new Todos(EntityState<int, TodoItem>.Empty.Add(new TodoItem(1, "Write docs", Done: false))));
store.Dispatch(new TodoToggled(1));
store.GetSlice<CartStore>().Add(new CartLine("duck-yellow", Quantity: 1));
await store.Settled();
store.State.WasRestored<Todos>().ShouldBeTrue();
store.State.Get<Todos>().Items.Find(1)!.Done.ShouldBeTrue();
store.State.Get<Cart>().Lines.Count.ShouldBe(1);
store.Processed.Where(context => context.Origin == Origin.Local).Select(context => context.ActionType)
.ShouldBe(["Ducky.Docs.Tests.Core.TodoToggled", "cart/Add"]);
store.Failures.ShouldBeEmpty();
}Createregisters aFakeTimeProvider(store.Time) and setsThrowOnUnhandledAction, so an action that no slice or effect handles is a failure. Set it back tofalseinconfigurewhen that is expected.Seedrestores a state as hydration does:State.WasRestored<TState>()becomes true.Settled()waits until the queue is empty and no effect runs, with a real-time bound (WallClockTimeout, 10 seconds), and throwsDuckyAssertionExceptionwhen it expires. LikeWhenIdleAsync, it doesn't wait forLongRunningeffects.Processedlists every action the store reduced (or whose reducer failed), with its origin, depth and correlation;FailureslistsReducerFailedandEffectFailed.GetSlice<CartStore>()returns the store-owned SliceStore, to call its methods.DisposeAsynchas the same real-time bound, so a test whose effect ignores cancellation fails instead of hanging.
Advance the fake clock with store.Time.Advance(...) to run timers and delays that effects create with context.Time.
Components
A component that selects from the store (DuckyComponent, DuckySelect) re-renders after the store commits: the store drains on its own thread, then posts a change check to the renderer. An assertion made right after a dispatch or an interaction can therefore run before the markup changes. WhenIdleAsync and Settled() only wait for the store.
After a dispatch or interaction, settle before asserting on markup. WhenRenderedAsync (Ducky.Blazor) waits until the store is idle and then until the render it requested has run:
Store.Dispatch(new SetItem(0, "changed"));
await Store.WhenRenderedAsync(Renderer.Dispatcher, Xunit.TestContext.Current.CancellationToken);
cut.Markup.ShouldBe("changed");To test a union slice or a union effect group on a TestStore, see Unions in Ducky.
It is async, so there is nothing to block on: DUCKY010 reports WhenRenderedAsync(...).GetAwaiter().GetResult() like the other Ducky tasks. Output that depends on the culture follows the render's execution context, which is empty (see #296).