Sub topic 14
Testing state transitions as plain functions
This chapter shows how to test the state logic you built in the earlier chapters without a widget tree, a test device, or a mocking library. The reduce function from the previous chapter takes a state and an event and returns the next state. Because it touches nothing else, ordinary unit tests can cover it completely.
What you need before this chapter
This chapter assumes you have read the earlier chapters on sealed classes, switch expressions, and record patterns. It reuses these types:
LoadState<T>withLoading,Loaded, andFailed.EventwithFetch,Succeeded, andErrored.reduceanddescribe.
You also need to know how to run dart test or flutter test and how expect and matchers work.
Why a pure function is easy to test
A pure function returns a value that depends only on its arguments, and it changes nothing outside itself. reduce fits that description. It reads a state and an event, then returns a new state. It never touches a network, a clock, or a widget.
That has three consequences for testing:
- You build the input values directly. There is nothing to mock.
- The test is synchronous, so you don't need
pumpAndSettleorawait. - A failing test points at one function and one input pair.
The code that performs the fetch, such as an HTTP call, belongs somewhere else. Its job is to turn the outcome into a Succeeded or Errored event and pass it to reduce. The reducer decides what happens next, and the surrounding code only carries out the I/O.
The diagram shows only the transitions that change something. reduce also defines a no-op: a Succeeded or Errored event arriving in Loaded or Failed returns the current state unchanged. That behaviour is easy to forget, so give it its own tests.
Setting up the test file
Put the types and functions in lib/load_state.dart and the tests in test/reduce_test.dart. This chapter calls the package app_state_demo. For pure Dart logic, package:test is enough, and flutter_test works the same way if your project already uses it.
name: app_state_demo
environment:
sdk: ^3.0.0
dev_dependencies:
test: ^1.24.0Writing the first tests
Each test builds an input pair, calls reduce, and checks the type and contents of the result.
import 'package:app_state_demo/load_state.dart';
import 'package:test/test.dart';
void main() {
group('reduce transitions', () {
test('Fetch from Loaded goes back to Loading', () {
final result = reduce(const Loaded(['a']), const Fetch());
expect(result, isA<Loading<List<String>>>());
});
test('Succeeded while Loading carries the items into Loaded', () {
final result = reduce(const Loading(), const Succeeded(['b', 'c']));
expect(
result,
isA<Loaded<List<String>>>().having((s) => s.data, 'data', ['b', 'c']),
);
});
test('Errored while Loading carries the error into Failed', () {
final result = reduce(const Loading(), const Errored('boom'));
expect(
result,
isA<Failed<List<String>>>().having((s) => s.error, 'error', 'boom'),
);
});
});
}Asserting on variants without ==
The state classes from this tutorial do not override ==. That means expect(result, const Loaded(['b'])) fails even when the contents match, because two Loaded objects are only equal if they are the same instance.
The matcher isA<Loaded<List<String>>>().having(...) solves this. It checks the runtime type first, then checks one field through a getter. A failure message names the field, for example data, so you can see which part was wrong.
If you would rather write expect(result, Loaded(['b'])), add == and hashCode to the variants, or use a package that generates them. Do that for a real reason, such as comparing states in a stream. Don't add it only to simplify tests, because the matchers above already work.
Testing the no-op cases
The last case in reduce returns the incoming state untouched. A test can assert that with same, which checks object identity.
import 'package:app_state_demo/load_state.dart';
import 'package:test/test.dart';
void main() {
group('reduce ignores late results', () {
test('Succeeded after Loaded keeps the existing state', () {
const state = Loaded<List<String>>(['a']);
final result = reduce(state, const Succeeded(['z']));
expect(result, same(state));
});
test('Errored after Failed keeps the first error', () {
const state = Failed<List<String>>('first');
final result = reduce(state, const Errored('second'));
expect(result, same(state));
});
});
}These tests record a design decision: late results are discarded. If you later decide that a late Errored should replace a Loaded, these tests fail on purpose and tell you which behaviour changed.
Covering every pair
The compiler already guarantees that reduce has a branch for every (state, event) pair. It does not guarantee that each branch does something sensible. A table-driven test fills that gap by looping over all combinations.
import 'package:app_state_demo/load_state.dart';
import 'package:test/test.dart';
void main() {
final states = <LoadState<List<String>>>[
const Loading(),
const Loaded(['a']),
const Failed('x'),
];
const events = <Event>[Fetch(), Succeeded(['b']), Errored('boom')];
group('every state and event pair', () {
for (final s in states) {
for (final e in events) {
test('${s.runtimeType} + ${e.runtimeType} returns a state', () {
expect(() => reduce(s, e), returnsNormally);
});
}
}
for (final s in states) {
test('Fetch from ${s.runtimeType} always yields Loading', () {
expect(reduce(s, const Fetch()), isA<Loading<List<String>>>());
});
}
});
}The first loop produces nine tests, one per pair. The second loop checks a rule that holds for every state: Fetch always starts loading. A rule that holds for all inputs is cheaper to test this way than by writing one case for each state.
When you add a new Event subclass, the compiler stops reduce from compiling until you handle it. The table above does not update itself, so add the new event to events. The new tests then fail if the branch you wrote is wrong.
| Concern | Who checks it |
|---|---|
| Every pair has a branch | The compiler, through exhaustiveness |
| Each branch returns the right state | Unit tests on specific pairs |
| A rule holds for all inputs | Table-driven loops |
| The UI shows the right widget | Widget tests |
Testing describe and guards
Functions that map a state to a value, such as describe, are also pure. Guards deserve extra attention because a guard splits one variant into two behaviours. In describe, Loaded with an empty list has a different result from Loaded with items. Test both sides of each when.
import 'package:app_state_demo/load_state.dart';
import 'package:test/test.dart';
void main() {
group('describe', () {
test('Loading', () {
expect(describe(const Loading()), 'Loading...');
});
test('Loaded with an empty list hits the guard', () {
expect(describe(const Loaded(<String>[])), 'Nothing here yet');
});
test('Loaded with items falls through to the general case', () {
expect(describe(const Loaded(['a', 'b'])), '2 items');
});
test('Failed', () {
expect(describe(const Failed('boom')), 'Error: boom');
});
});
}The empty list and the two-item list sit on opposite sides of the when items.isEmpty guard. A single Loaded test would pass whichever branch it hit, and the other branch would stay untested.
Where pure tests stop
Reducer tests prove that the logic maps each state and event to the right next state. They do not prove that:
- The widget shows a spinner for
Loading. - Your fetch code sends
Erroredwhen a request fails. - The state is held and updated somewhere in the app, for example in a
StatefulWidgetor a state-management package.
Cover those with a widget test and a test for the fetching code. Keep them small, because the reducer tests already cover the branching. A widget test can build ItemsView with a hand-made Loaded state and check for the expected ListTile widgets. The widget test then needs no reducer, no fake network, and no waiting.
Common mistakes
- Using a wildcard in
reduceto shorten it. A_ => statebranch makes the switch exhaustive for every future event, and the compiler stops warning you about unhandled pairs. If the reducer has one, your tests are the only safety net. Prefer listing the cases. - Comparing states with
==when none is defined. The test fails even though the values match. UseisAwithhaving, or define equality deliberately. - Testing only the happy path. Cover the no-op pairs and the guard edges, because that is where bugs hide in a
reducefunction. - Putting I/O inside
reduce. Once the function awaits a network call, you need fakes and async tests again. Keep it pure and move I/O out. - Forgetting to update the table. The compiler catches a missing branch, but it can't tell you that your loop over
eventsis missing the new event.
Exercise
The app gains a new event, Cancel, which should move Loading back to a new state Idle and leave Loaded and Failed unchanged. Which parts of your code and tests must change, and which problems will the compiler report for you?
Show answer
The compiler reports that reduce is no longer exhaustive for (state, event) once Cancel and Idle are added to the sealed hierarchies, and it also reports every other switch over LoadState (such as describe and ItemsView) that has no Idle case. You fix each of those by adding the missing branches. The compiler does not update your tests. Add Cancel() to the events list and Idle() to the states list in the table-driven test, and write explicit tests that Loading + Cancel gives Idle, and that Loaded + Cancel and Failed + Cancel return the same instance, checked with same.