dart-migrate-to-checks-package

视觉设计 / 插画 界面 · 动效 · 设计品味 1 文件 EN 原文

Replace the usage of `expect` and similar functi

Replace the usage of `expect` and similar functions from `package:matcher` to `package:checks` equivalents.

说明语言:英文

来源flutteragent-plugins ↗ 查看原文件 ↗版权归原作者,请遵循原仓库许可
安装
npx skills add https://github.com/flutter/agent-plugins --skill dart-migrate-to-checks-package

需要已安装 skills CLI。也可以直接从源仓库 clone。

在星云中查看 ↗
SKILL.md 原文

name: dart-migrate-to-checks-package description: |- Replace the usage of expect and similar functions from package:matcher to package:checks equivalents. metadata: model: models/gemini-3.1-pro-preview last_modified: Tue, 09 Jun 2026 19:30:00 GMT ---

Migrating Dart Tests to Package Checks

Use this skill when you need to migrate a Dart test suite from the legacy package:matcher (which is exported by default from package:test/test.dart) to the modern, type-safe, and literate package:checks assertion library.

Contents


When to Use This Skill


How to Use This Skill (The Workflow)

Follow this structured workflow to safely and systematically migrate a test suite:

1. Dependency Setup

  dart pub add dev:checks

2. Identify and Plan Target Files

3. Migrating a File (Incremental or Full)

For any target test file:

  1. Update Imports:
  2. Replace the generic import 'package:test/test.dart'; with:
     import 'package:test/scaffolding.dart';
     import 'package:checks/checks.dart';
     import 'package:test/expect.dart'; // Temporarily allows legacy expect()
  1. Translate Assertions: Rewrite legacy expect and expectLater calls to check syntax following the Key Syntax Differences and Pitfalls and the Matcher-to-Checks Mapping Table.
  2. Verify via Compiler: If migrating fully, remove the import 'package:test/expect.dart'; line. Any remaining un-migrated expect calls will immediately surface as compiler errors, making them easy to find and fix.

4. Verification and Feedback Loops

  dart analyze

Pay close attention to generic type parameters on .isA<Type>() and ensure asynchronous expectations are properly awaited (check for unawaited_futures warnings).

  dart test

If a test fails, review the extremely detailed failure output of package:checks to diagnose if the test is genuinely failing or if the expectation was translated incorrectly.


Key Syntax Differences and Pitfalls

[!IMPORTANT] A line-for-line translation can sometimes introduce subtle bugs or false passes. Always review these key differences carefully:

1. Collection Equality Pitfall (equals vs deepEquals)

  // BEFORE (Matcher)
  expect(myList, [1, 2, 3]);

  // AFTER (Checks)
  check(myList).deepEquals([1, 2, 3]);

2. The reason Parameter is now because

  expect(actual, expectation, reason: 'Explanation');
  check(because: 'Explanation', actual).expectation();

3. Regular Expression Matching (matches vs matchesPattern)

  // BEFORE (Matcher)
  expect(someString, matches(r'\d+'));

  // AFTER (Checks)
  check(someString).matchesPattern(RegExp(r'\d+'));

4. Property Extraction (TypeMatcher.having vs .has)

  expect(actual, isA<Person>().having((p) => p.name, 'name', startsWith('A')));
  check(actual).isA<Person>().has((p) => p.name, 'name').startsWith('A');

5. Synchronous vs. Asynchronous throws

    // YES (Synchronous chaining)
    check(() => triggerSyncError()).throws<ArgumentError>()
      ..has((e) => e.message, 'message').equals('invalid input');

    // NO (Passing a callback to sync throws will cause a compiler error!)
    check(() => triggerSync").throws<ArgumentError>((it) => ...); // ERROR!
    // YES (Asynchronous callback)
    await check(triggerAsyncError()).throws<ArgumentError>((it) => it
      ..has((e) => e.message, 'message').equals('invalid input'));

6. RegExp / Pattern Equality

  check(myPattern).isA<RegExp>()
    ..has((r) => r.pattern, 'pattern').equals('Hello')
    ..has((r) => r.isMultiLine, 'isMultiLine').isTrue();

7. Strict Nullable Boolean Safety (bool? fields)

  // If options.flagOutdated is a bool?
  check(options.flagOutdated).equals(true);
  check(options.flagOutdated).equals(false);

8. Map Key Containment (containsKey vs contains)

  // BEFORE (Matcher)
  expect(myMap, contains('my_key'));

  // AFTER (Checks)
  check(myMap).containsKey('my_key');

9. Explicit Generic Parameters for Extension Types

  // YES (Type-safe and warning-free)
  check<int>(QrEciValue.iso8859_1).equals(3);

10. Dynamic Map / JSON Lookup Casting

  // YES (Explicit cast to List)
  check(myIterable).deepEquals(json['data']['items'] as List);

Matcher-to-Checks Mapping Table

Use this table as a quick reference for direct matcher replacements:

Legacy MatcherPackage Checks EquivalentNotes
expect(actual, expected)check(actual).equals(expected)Use .deepEquals for collections!
expect(actual, equals(expected))check(actual).equals(expected)Use .deepEquals for collections!
isA<T>()check(actual).isA<T>()Chaining is supported directly
same(expected)check(actual).identicalTo(expected)Verifies identity
anyElement(matcher)check(iterable).any(conditionCallback)E.g. check(list).any((e) => e.equals(1))
everyElement(matcher)check(iterable).every(conditionCallback)E.g. check(list).every((e) => e.isGreaterThan(0))
hasLength(expected)check(actual).length.equals(expected)Works on String, Map, Iterable, etc.
isNot(matcher)check(actual).not(conditionCallback)E.g. check(val).not((it) => it.equals(5))
contains(element)check(actual).contains(element)Works on String, Iterable (use containsKey for Map!)
contains(key) (on a Map)check(map).containsKey(key)Map key containment
startsWith(prefix)check(string).startsWith(prefix)String only
endsWith(suffix)check(string).endsWith(suffix)String only
isEmptycheck(actual).isEmpty()Works on String, Map, Iterable
isNotEmptycheck(actual).isNotEmpty()Works on String, Map, Iterable
isNullcheck(actual).isNull()
isNotNullcheck(actual).isNotNull()
isTrue / truecheck(actual).isTrue()Works on non-nullable bool only
isFalse / falsecheck(actual).isFalse()Works on non-nullable bool only
completion(matcher)await check(future).completes(conditionCallback)Must be awaited!
throwsA(matcher)await check(future).throws<Type>()Must be awaited!
emits(value)await check(streamQueue).emits(conditionCallback)Must be awaited!
emitsThrough(value)await check(streamQueue).emitsThrough(conditionCallback)Must be awaited!
stringContainsInOrder(list)check(string).containsInOrder(list)String only
pairwiseCompare(...)check(actual).pairwiseMatches(...)

Matchers with No Direct Replacements

Some legacy matchers do not have a one-to-one equivalent in package:checks due to API cleanup. Use these standard workarounds:

1. Specific Error Matchers

  await check(triggerError()).throws<ArgumentError>();

2. The anything Matcher

  await check(someFuture).completes((_) {});

3. Specific Numeric Toggles

4. Numeric Ranges

  check(actualValue)
    ..isGreaterOrEqual(min)
    ..isLessThan(max);

Writing Custom Expectations (Replacing Custom Matchers)

When migrating from a legacy codebase, you may encounter custom Matcher subclasses. In package:checks, custom assertions are implemented as extension methods on Subject<T>.

To write custom expectations, you must import the checks context API:

import 'package:checks/context.dart';

1. Simple Custom Expectations (using expect)

Use context.expect to check a property and return a Rejection on failure:

extension CustomPersonChecks on Subject<Person> {
  void isAdult() {
    context.expect(
      () => ['is an adult (age >= 18)'],
      (actual) {
        if (actual.age >= 18) return null; // Pass
        return Rejection(
          which: ['is only ${actual.age} years old'],
        );
      },
    );
  }
}

2. Nested Property Extraction (using nest or has)

To extract a property and allow further chained checks, use nest or the simpler has helper:

  extension CustomPersonChecks on Subject<Person> {
    Subject<Address> get address => has((p) => p.address, 'address');
  }
  extension CustomPersonChecks on Subject<Person> {
    Subject<String> get ssn => context.nest(
      'has a valid SSN',
      (actual) {
        final ssnValue = actual.ssn;
        if (ssnValue == null) {
          return Extracted.rejection(which: ['has no SSN']);
        }
        return Extracted.value(ssnValue);
      },
    );
  }

3. Asynchronous Custom Expectations

If the expectation is asynchronous (e.g. checking a Future or Stream), use context.expectAsync or context.nestAsync and return the resulting Future:

extension CustomFutureChecks<T> on Subject<Future<T>> {
  Future<void> completesNormally() {
    return context.expectAsync(
      () => ['completes without throwing'],
      (actual) async {
        try {
          await actual;
          return null; // Pass
        } catch (e) {
          return Rejection(which: ['threw $e']);
        }
      },
    );
  }
}

Strategies for Discovery

Execute these commands in the terminal to identify legacy matchers and files requiring migration:

# 1. Find all test files containing legacy expect() or expectLater()
grep -rn "expect(" test/
grep -rn "expectLater(" test/

# 2. Find potential collection equality pitfalls (literal lists or maps)
grep -rn "expect(.*, \[" test/
grep -rn "expect(.*, {" test/

# 3. Find matches() calls (need conversion to RegExp + matchesPattern)
grep -rn "matches(" test/

# 4. Find legacy TypeMatcher.having() calls (which need conversion to .has())
grep -rn "having(" test/

Examples

Basic Assertions

Before (Matcher):

expect(someValue, isNotNull);
expect(result, isTrue, reason: 'should be successful');
expect(myString, startsWith('hello'));

After (Checks):

check(someValue).isNotNull();
check(because: 'should be successful', result).isTrue();
check(myString).startsWith('hello');

Collection and Deep Equality

Before (Matcher):

expect(items, [1, 2, 3]);
expect(configMap, equals({'port': 8080}));

After (Checks):

check(items).deepEquals([1, 2, 3]);
check(configMap).deepEquals({'port': 8080});

Chaining and Cascades

Before (Matcher):

expect(someString, allOf([
  startsWith('a'),
  contains('b'),
  endsWith('c'),
]));

After (Checks):

check(someString)
  ..startsWith('a')
  ..contains('b')
  ..endsWith('c');

Complex Property Matching (has)

Before (Matcher):

expect(response, isA<Response>()
    .having((r) => r.statusCode, 'statusCode', 200)
    .having((r) => r.body, 'body', contains('success')));

After (Checks):

check(response).isA<Response>()
  ..has((r) => r.statusCode, 'statusCode').equals(200)
  ..has((r) => r.body, 'body').contains('success');

Asynchronous Futures

Before (Matcher):

expect(fetchData(), completes);
expect(fetchData(), completion(equals('data')));
expect(failingCall(), throwsA(isA<StateError>()));

After (Checks):

await check(fetchData()).completes();
await check(fetchData()).completes((it) => it.equals('data'));
await check(failingCall()).throws<StateError>();

Asynchronous Streams

Before (Matcher):

var queue = StreamQueue(Stream.fromIterable([1, 2, 3]));
await expectLater(queue, emitsInOrder([1, 2, 3]));

After (Checks):

var queue = StreamQueue(Stream.fromIterable([1, 2, 3]));
await check(queue).inOrder([
  (s) => s.emits((e) => e.equals(1)),
  (s) => s.emits((e) => e.equals(2)),
  (s) => s.emits((e) => e.equals(3)),
]);
同类技能
accessibilityaccessibility-complianceanimateanimate-expoanimation-performanceanimation-vocabularyanti-ui-slopapple-design
本页内容来自开源项目 flutter, 版权归原作者所有。
本站仅作技能索引与分享,所有 Skill 版权归其原作者所有。