Testing
A test instance
Build an Authyra with InMemoryAuthStorage and a provider backed by fakes. Turn the scheduler off unless the test is about it.
import 'package:authyra/authyra.dart';
import 'package:test/test.dart';
void main() {
test('a rejected refresh token signs the user out', () async {
final authyra = Authyra(
storage: InMemoryAuthStorage(),
config: const AuthyraConfig(autoRefresh: false),
providers: [
CredentialsProvider(
id: 'api',
signIn: (_) async => AuthSignInResult(
user: const AuthUser(id: 'ada'),
tokens: AuthTokens.expiringIn(
const Duration(minutes: 15),
accessToken: 'a1',
refreshToken: 'r1',
),
),
refresh: (_) async => throw const RefreshRevokedException(),
),
],
);
addTearDown(authyra.dispose);
await authyra.start();
await authyra.signIn(
'api',
params: const CredentialsSignInParams(identifier: 'ada', password: 'x'),
);
expect(await authyra.accessToken(rejectedToken: 'a1'), isNull);
expect(authyra.state, const AuthSignedOut());
});
}
InMemoryAuthStorage.entries exposes what was persisted, for assertions. Pass initial entries to the constructor to test a restore.
Time
Authyra reads time through package:clock. With fake_async, scheduled refreshes and backoff run instantly:
fakeAsync((async) {
// Create Authyra, sign in with a token expiring in 2 minutes...
async.elapse(const Duration(minutes: 1, seconds: 1));
// The scheduled refresh has run.
});
Build token expiries with clock.now() or AuthTokens.expiringIn, never DateTime.now(), or fake time and token time disagree.
Widget tests
- Create the instance in the test body, not in
setUp:testWidgetsruns the body in a fake-async zone, and streams created outside it are not flushed bytester.pump. - Dispose it with
addTearDown(authyra.dispose). - Use
pumpAndSettleafter an action whose state change must reach a widget. testWidgetsruns under a fake clock set in 2015: build expiries withclock.now().
testWidgets('shows the home screen once signed in', (tester) async {
final authyra = Authyra(
storage: InMemoryAuthStorage(),
config: const AuthyraConfig(autoRefresh: false), // No timer left pending.
providers: [fakeProvider],
);
addTearDown(authyra.dispose);
await authyra.start();
await tester.pumpWidget(AuthyraScope(authyra: authyra, child: const App()));
expect(find.byType(SignInScreen), findsOneWidget);
await authyra.signIn('api', params: credentials);
await tester.pumpAndSettle();
expect(find.byType(HomeScreen), findsOneWidget);
});
Testing a provider alone
Providers are plain classes: call signIn and refresh directly, with an HTTP client you control. OAuth2Provider and BackendOAuthProvider accept an httpClient (for example MockClient from package:http/testing.dart) and a browser function that returns the redirect URL without opening a browser.