小部件测试使用 WidgetsBinding.instance.addPostFrameCallback() 的小部件

Widget test a widget which uses WidgetsBinding.instance.addPostFrameCallback()

我正在尝试对一个小部件进行 flutter 测试,该小部件使用 WidgetsBinding.instance.addPostFrameCallback() 在小部件生命周期的最开始显示对话框。

小部件工作正常,但我不知道如何进行小部件测试,因为测试的第一个 expect() 是在触发此 post 帧之前执行的。

"tell" 测试是否要等到所有 post 帧都被分派?

PD:tester.pump()、tester.pumpAndSettle() 等 工作。

但是你知道什么...突然弹出:

    tester.binding.scheduleWarmUpFrame();

运行 即:-)

取自此处:https://chromium.googlesource.com/external/github.com/flutter/flutter/+/v0.9.2/packages/flutter/test/widgets/binding_test.dart

这对我有用:

// press button
await tester.tap(find.text("Save"));
// await the flushbar or snackbar to appear
await tester.pumpAndSettle(const Duration(seconds: 1));
// find by text or key
expect(find.text("Error saving note"), findsOneWidget);
// this prevents this error:
// A Timer is still pending even after the widget tree was disposed.
// the flushbar in my code is displayed for 5 seconds. So we wait for it to 
// go away.
await tester.pumpAndSettle(const Duration(seconds: 5));

我不知道这样做是否正确。但它有效。 祝你好运!

要在 flutter 测试环境中安排帧(并强制调用 postFrameCallback),您需要在 tester.pump() 之前调用 tester.binding.scheduleFrame()

或者,如果您不关心正在重建的整个小部件树,您可以调用 tester.pumpWidget(widget) 而不是 tester.pump()

示例测试:

testWidgets('testing frames', (tester) async {
  final w = Container();
  int framesCount = 0;

  tester.binding.addPersistentFrameCallback((timeStamp) {
    framesCount++;
  });

  await tester.pumpWidget(w);
  expect(framesCount, equals(1));

  // pumpWidget calls [scheduleFrame]
  await tester.pumpWidget(w);
  expect(framesCount, equals(2));

  await tester.pump();
  // no frame was scheduled, so framesCount is still 2
  expect(framesCount, equals(2));

  tester.binding.scheduleFrame(); // --
  await tester.pump();            //   |
  expect(framesCount, equals(3)); // <-

  // pumpWidget calls [scheduleFrame]
  await tester.pumpWidget(w);
  expect(framesCount, equals(4));
});