Flutter FadeInImage 测试

问题描述 投票:0回答:1

我一直在尝试为

FadeInImage
编写一个简单的测试,但没有成功。我只是想测试
kTransparentImage
是否显示为占位符。然后经过一定的等待时间(默认700ms),URL图像出现并且
kTransparentImage
消失。

首先我们需要使用

HttpClient
来显示网络图像。我使用
nock
,但请随意使用您自己的。

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:transparent_image/transparent_image.dart';

void main() {
  testWidgets('Test FadeInImage', (tester) async {
    await tester.pumpWidget(FadeInImage.memoryNetwork(
      placeholder: kTransparentImage,
      image: 'https://picsum.photos/id/28/200',
    ));

    // First: Solve for "provide your own HttpClient implementation" error

    // Second: Test for placeholder image (kTransparentImage)

    // Third: Wait until network image to appear

    // Forth: Test for network image (https://picsum.photos/id/28/200)
  });
}
flutter dart
1个回答
0
投票

您需要解决几个关键点:提供您自己的

HttpClient
实现、测试占位符图像 (
kTransparentImage
)、等待网络图像出现、测试网络图像。

通过这样做,您可以测试

FadeInImage
小部件;

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:transparent_image/transparent_image.dart';
import 'package:http/http.dart' as http;

class MockHttpClient extends http.BaseClient {
  @override
  Future<http.StreamedResponse> send(http.BaseRequest request) async {
    return http.StreamedResponse(null, 200);
  }
}

void main() {
  testWidgets('Test FadeInImage', (tester) async {
    // Provide your own HttpClient implementation
    http.Client client = MockHttpClient();

    await tester.pumpWidget(MaterialApp(
      home: FadeInImage.memoryNetwork(
        placeholder: kTransparentImage,
        image: 'https://picsum.photos/id/28/200',
        client: client,
      ),
    ));

    // Test for placeholder image (kTransparentImage)
    expect(find.byWidgetPredicate((widget) => widget is FadeInImage && widget.placeholder == kTransparentImage), findsOneWidget);

    // Wait for 700ms
    await Future.delayed(Duration(milliseconds: 700));

    // Test for network image (https://picsum.photos/id/28/200)
    expect(find.byWidgetPredicate((widget) => widget is FadeInImage && widget.image == 'https://picsum.photos/id/28/200'), findsOneWidget);
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.