rulila52 / adaptive-scrollbar

MIT License
11 stars 7 forks source link

Fix "Timer is still pending" error when running tests #5

Open cassioso opened 8 months ago

cassioso commented 8 months ago

This PR fixes an exception that is thrown when running widget tests.

Using Future.delayed inside the build() function + not cancelling the Timer instance on the widget disposal don't play well with flutter tests.

When testing the current code the following exception will be thrown:

══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following assertion was thrown running a test:
A Timer is still pending even after the widget tree was disposed.
'package:flutter_test/src/binding.dart':
Failed assertion: line 1518 pos 12: '!timersPending'

Watching the tests logs you will find a hint:

Pending timers:
Timer (duration: 0:00:00.400000, periodic: false), created:
#0      new FakeTimer._ (package:fake_async/fake_async.dart:308:62)
#1      FakeAsync._createTimer (package:fake_async/fake_async.dart:252:27)
#2      FakeAsync.run.<anonymous closure> (package:fake_async/fake_async.dart:185:19)
#5      new _ScrollSliderState (package:adaptive_scrollbar/adaptive_scrollbar.dart:348:17)
#6      ScrollSlider.createState (package:adaptive_scrollbar/adaptive_scrollbar.dart:319:39)
#7      new StatefulElement (package:flutter/src/widgets/framework.dart:5555:25)
Screenshot 2024-02-23 at 17 33 19

The exception can be reproduced by replacing the main function in ...example/test/widget_test.dart by the following:

void main() {
  testWidgets('Simple test', (WidgetTester tester) async {
    await tester.pumpWidget(MyApp());
  });
}

Running the same test with the changes in this PR will result in passing tests ✅