颤动中的提供者的单元测试 [英] Unit Testing for Providers in Flutter

查看:9
本文介绍了颤动中的提供者的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们已经在TDD方法中启动了一个关于颤振的新项目。我正在使用国家管理的提供者。 在尝试编写Widget测试时,我们面临着测试提供者的问题。 您能举出一个例子来建议编写提供者的单元测试和Widget注入提供者的方法吗?

我遇到以下问题

══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════
The following ProviderNotFoundException was thrown running a test:
Error: Could not find the correct Provider above this SplashScreen Widget

To fix, please:

Ensure the Provider is an ancestor to this SplashScreen Widget
Provide types to Provider
Provide types to Consumer
Provide types to Provider.of()
Always use package imports. Ex: `import 'package:my_app/my_code.dart';
Ensure the correct context is being used.

══╡闪屏代码╞════════════════════════════════════

import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../routes.dart';
import '../../constants/constants.dart';
import '../../providers/provider.dart';
import '../../services/navigation_service.dart';
import '../../utils/utlis.dart';

class SplashScreen extends StatefulWidget {
  @override
  SplashScreenState createState() => SplashScreenState();
}

class SplashScreenState extends State {
  void startTime() {
    const _duration = Duration(seconds: Preferences.splashScreenTime);
    Timer(_duration, _getInitialData);
    _getInitialData();
  }

  dynamic _getInitialData() async {
    final TokenProvider tokenProvider =
    Provider.of(context, listen: false);

    await tokenProvider.setAccessToken();

    navigationPage();
  }

  void navigationPage() {
    NavigationService.pushReplacementNamedTo(Routes.home_screen);
  }

  @override
  void initState() {
    super.initState();
    startTime();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Stack(
        key: const Key('splashScreen_body'),
        fit: StackFit.expand,
        children: [
          Image.asset(
            'assets/images/flutter.png',
            key: const Key('splashScreen_image'),
          )
        ],
      ),
    );
  }
}

提前感谢

推荐答案

您需要包装要在该小部件使用的提供程序中测试的小部件。

因此,您可以这样写:

await tester.pumpWidget(
  Provider<TokenProvider>(
    child: SplashScreen(),
  ),
);

这篇关于颤动中的提供者的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆