### Dart Test Setup and Teardown with Spec Source: https://context7.com/invertase/spec/llms.txt This example demonstrates how to manage test setup and teardown using Spec, which re-exports standard test lifecycle functions. It shows setUpAll and tearDownAll for one-time setup/teardown before/after all tests, and setUp and tearDown for setup/teardown before/after each individual test. ```dart import 'package:spec/spec.dart'; void main() { late Database db; late HttpClient client; setUpAll(() async { // Run once before all tests in this file db = await Database.connect('test_db'); }); tearDownAll(() async { // Run once after all tests complete await db.close(); }); setUp(() { // Run before each test client = HttpClient(); }); tearDown(() { // Run after each test client.close(); }); group('Database tests', () { test('can insert record', () async { await db.insert({'name': 'test'}); expect(await db.count()).toEqual(1); }); test('can query records', () async { final results = await db.query('SELECT * FROM records'); expect(results).not.toBeNull(); }); }); } ``` -------------------------------- ### Spec CLI Installation and Usage Source: https://github.com/invertase/spec/blob/main/README.md Provides instructions for installing the Spec CLI globally using Dart Pub and demonstrates basic usage commands for running tests and entering watch mode. ```bash dart pub global activate spec_cli ``` ```bash spec ``` ```bash spec --watch ``` -------------------------------- ### Install and Run Spec CLI Source: https://context7.com/invertase/spec/llms.txt Installs the Spec CLI globally and provides commands to run tests, including an interactive watch mode with keyboard shortcuts for filtering and re-running tests. ```bash # Install the CLI globally dart pub global activate spec_cli # Run tests spec # Run tests in interactive watch mode spec --watch # Watch mode keyboard shortcuts: # Press f to run only failed tests # Press t to filter by a test name regex pattern # Press q to quit watch mode # Press Enter to trigger a test run ``` -------------------------------- ### Installing Spec CLI (Bash) Source: https://github.com/invertase/spec/blob/main/docs/index.mdx Provides the command to globally activate the Spec CLI tool using Dart's package manager. This enables the use of the `spec` command in the terminal for running tests. ```bash dart pub global activate spec_cli ``` -------------------------------- ### Dart Test Example with Spec Package Source: https://github.com/invertase/spec/blob/main/packages/spec_cli/README.md Demonstrates how to write type-safe tests using the 'spec' Dart package, contrasting it with traditional 'expect' assertions. It highlights the declarative 'toEqual' and 'completion.toEqual' syntax provided by the package. ```dart test('dart test example', () async { int value = 42; // Without spec - not type safe expect(value, equals(42)); await expectLater(Future.value(42), completion(equals(42))); // With spec - type safe expect(value).toEqual(42); await expect(Future.value(42)).completion.toEqual(42); }); ``` -------------------------------- ### Testing Futures, Streams, and Functions with Spec Matchers (Dart) Source: https://github.com/invertase/spec/blob/main/docs/index.mdx Demonstrates how to use Spec's custom matchers for testing asynchronous operations like Futures and Streams, as well as synchronous functions that may throw errors. This example showcases `completion`, `emits`, `emitsError`, `throws`, `returnsNormally`, and negation operators. ```dart import 'package:spec/spec.dart'; void main() { test('future example', () async { final future = Future.value(42); expect(future).toEqual(future); await expect(future).completion.toEqual(42); await expect(future).throws.isArgumentError(); }); test('stream example', () async { final stream = Stream.value(42); await expect(stream).emits.toEqual(42); await expect(stream).emits.isNull(); await expect(stream).emits.not.isNull(); await expect(stream).emitsError.isArgumentError(); }); test('function example', () { void throwsFn() => throw Error(); expect(throwsFn).returnsNormally(); expect(throwsFn).throws.isArgumentError(); }); } ``` -------------------------------- ### Filter Dart Test Protocol Events with dart_test_adapter Source: https://context7.com/invertase/spec/llms.txt This snippet shows how to filter specific event types from the Dart test protocol stream using the dart_test_adapter package. It demonstrates how to capture 'TestEventTestStart' events and print details about the starting tests, including their names, suite IDs, group IDs, and location. ```dart import 'package:dart_test_adapter/dart_test_adapter.dart'; void main() async { // Filter specific event types from test stream final testStarts = dartTest() .where((e) => e is TestEventTestStart) .cast(); // Print test names as they start await for (final start in testStarts) { print('Starting: ${start.test.name}'); print(' Suite ID: ${start.test.suiteID}'); print(' Groups: ${start.test.groupIDs}'); print(' Location: ${start.test.url}:${start.test.line}'); } } // Available TestEvent types: // - TestEventStart: Test runner started // - TestEventDone: All tests completed // - TestEventAllSuites: Total suite count known // - TestEventSuite: Suite loaded // - TestEventGroup: Group encountered // - TestEventTestStart: Individual test starting // - TestEventTestDone: Individual test completed (with result, skipped status) // - TestEventMessage: Print/skip message from test // - TestEventTestError: Test error with stack trace // - TestEventDebug: Debug information (with --debug flag) // - TestProcessDone: Test process exited // - TestEventUnknown: Unrecognized event type ``` -------------------------------- ### Running Spec Tests (Bash) Source: https://github.com/invertase/spec/blob/main/docs/index.mdx Shows the basic command to execute tests using the Spec CLI. This command will discover and run all tests in the project. ```bash spec ``` -------------------------------- ### Running Spec Tests in Watch Mode (Bash) Source: https://github.com/invertase/spec/blob/main/docs/index.mdx Demonstrates how to run Spec tests in an interactive watch mode. This mode automatically re-runs tests when source files change and provides options to re-run only failed tests or filter by test name. ```bash spec --watch ``` -------------------------------- ### Execute Dart and Flutter Tests Source: https://github.com/invertase/spec/blob/main/packages/dart_test_adapter/README.md These functions execute 'dart test' or 'flutter test' and return a Stream of events representing the Dart Test protocol. This allows for programmatic handling of test results, such as filtering and processing specific event types. ```dart dartTest(); flutterTest(); ``` ```dart dartTest() .where((e) => e is TestEventTestStart) .cast() .forEach((start) => print(start.test.name)); ``` -------------------------------- ### Programmatic Dart Test Execution with dartTest() Source: https://context7.com/invertase/spec/llms.txt The `dartTest()` function executes `dart test` and returns a stream of test protocol events for programmatic monitoring. It requires the 'dart_test_adapter' package and takes arguments for test execution, such as working directory, test files, and environment variables. ```dart import 'package:dart_test_adapter/dart_test_adapter.dart'; void main() async { // Run dart test and stream events final events = dartTest( workdingDirectory: '/path/to/project', arguments: ['--coverage'], tests: ['test/unit_test.dart'], environment: {'DART_VM_OPTIONS': '--enable-asserts'}, ); // Listen to test events await for (final event in events) { switch (event) { case TestEventStart(:final protocolVersion, :final pid): print('Test runner started (v$protocolVersion, pid: $pid)'); break; case TestEventSuite(:final suite): print('Loading suite: ${suite.path}'); break; case TestEventTestStart(:final test): print('Running: ${test.name}'); break; case TestEventTestDone(:final testID, :final result, :final skipped): print('Test $testID: ${skipped ? "SKIPPED" : result.name}'); break; case TestEventTestError(:final error, :final stackTrace): print('Error: $error\n$stackTrace'); break; case TestEventDone(:final success): print('All tests ${success == true ? "passed" : "failed"}'); break; case TestProcessDone(:final exitCode): print('Process exited with code: $exitCode'); break; default: break; } } } ``` -------------------------------- ### Verify Boolean Values with Simple Matchers Source: https://context7.com/invertase/spec/llms.txt Use straightforward matchers to assert boolean states, checking if a value is true or false. Also supports checking for truthy and falsy values, including null. ```dart import 'package:spec/spec.dart'; void main() { test('boolean assertions', () { expect(true).isTrue(); expect(false).isFalse(); // Using negation expect(true).not.isFalse(); expect(false).not.isTrue(); // Truthy/Falsy (also works with null) expect(true).toBeTruthy(); expect(false).toBeFalsy(); expect(null).toBeFalsy(); }); } ``` -------------------------------- ### Verify Map Key-Value Pairs and Properties Source: https://context7.com/invertase/spec/llms.txt Assert properties of maps, including checking for the existence of keys, values, and specific key-value pairs. Also supports verifying the total number of entries in the map. ```dart import 'package:spec/spec.dart'; void main() { test('map assertions', () { final config = { 'host': 'localhost', 'port': 8080, 'debug': true, }; // Check for key existence expect(config).containsKey('host'); expect(config).toContain('port'); // toContain also works for keys // Check for value existence expect(config).containsValue('localhost'); expect(config).containsValue(8080); // Check for specific key-value pair expect(config).containsPair('host', 'localhost'); expect(config).containsPair('port', 8080); // Length check expect(config).toHaveLength(3); }); } ``` -------------------------------- ### Dart: Testing Future Assertions with expect() Source: https://context7.com/invertase/spec/llms.txt Shows how to test asynchronous Future operations using Spec's `expect()` function with `.completion` and `.throws` modifiers. It includes checks for expected values, errors, and non-completing Futures. ```dart import 'package:spec/spec.dart'; void main() { test('future completion', () async { final future = Future.value(42); // Test that future completes with expected value await expect(future).completion.toEqual(42); await expect(future).completion.not.toBeNull(); // Test future identity (synchronous) expect(future).toEqual(future); }); test('future errors', () async { final failingFuture = Future.error(ArgumentError('invalid')); // Test that future throws specific error types await expect(failingFuture).throws.isArgumentError(); await expect(failingFuture).throws.isA(); // Test future that should not complete final neverCompletes = Future.delayed(Duration(days: 365)); expect(neverCompletes).doesNotComplete(); }); } ``` -------------------------------- ### Programmatic Flutter Test Execution with flutterTest() Source: https://context7.com/invertase/spec/llms.txt The `flutterTest()` function executes `flutter test` and provides a stream of test protocol events, similar to `dartTest()`. This allows for programmatic monitoring and result aggregation of Flutter tests. It requires the 'dart_test_adapter' package. ```dart import 'package:dart_test_adapter/dart_test_adapter.dart'; void main() async { // Run flutter test and collect results final results = {}; final tests = {}; await for (final event in flutterTest( workdingDirectory: '/path/to/flutter/project', arguments: ['--reporter=json'], tests: ['test/widget_test.dart'], )) { if (event is TestEventTestStart) { tests[event.test.id] = event.test.name; } else if (event is TestEventTestDone && !event.hidden) { final testName = tests[event.testID] ?? 'Unknown'; results[testName] = event.result; } else if (event is TestProcessDone) { print('\n=== Test Results ==='); results.forEach((name, status) { final icon = status == TestDoneStatus.success ? '✓' : '✗'; print('$icon $name'); }); final passed = results.values.where((s) => s == TestDoneStatus.success).length; final total = results.length; print('\n$passed/$total tests passed'); } } } ``` -------------------------------- ### Perform String Assertions with Case-Insensitive and Whitespace Handling Source: https://context7.com/invertase/spec/llms.txt Validate string content using various matchers, including case-insensitive comparison, ignoring leading/trailing whitespace, and checking for substrings or patterns. Supports checking for substrings in a specific order. ```dart import 'package:spec/spec.dart'; void main() { test('string equality', () { expect('Hello World').toEqual('Hello World'); // Case-insensitive comparison expect('HELLO').equalsIgnoringCase('hello'); expect('Hello World').equalsIgnoringCase('HELLO WORLD'); }); test('whitespace handling', () { // Ignores leading/trailing whitespace and collapses internal whitespace expect(' hello world ').equalsIgnoringWhitespace('hello world'); expect('hello\n\tworld').equalsIgnoringWhitespace('hello world'); }); test('string patterns', () { expect('Hello World').startsWith('Hello'); expect('Hello World').toContain('lo Wo'); expect('Hello World').toMatch(RegExp(r'H.*d')); // Check substrings appear in order expect('abcdefghij').stringContainsInOrder(['abc', 'def', 'hij']); }); } ``` -------------------------------- ### Dart: Testing Stream Assertions with expect() Source: https://context7.com/invertase/spec/llms.txt Illustrates testing Stream emissions and errors in Dart using Spec's `expect()` function with `.emits`, `.emitsError`, and `.emitsDone` modifiers. It covers checking emitted values, stream errors, and stream completion. ```dart import 'package:spec/spec.dart'; void main() { test('stream emissions', () async { final stream = Stream.fromIterable([1, 2, 3]); // Test next emitted value await expect(stream).emits.toEqual(1); await expect(stream).emits.not.isNull(); await expect(stream).emits.isA(); }); test('stream errors', () async { final errorStream = Stream.error(FormatException('bad format')); // Test that stream emits specific error await expect(errorStream).emitsError.isFormatException(); await expect(errorStream).emitsError.isA(); }); test('stream completion', () async { final finiteStream = Stream.fromIterable([1, 2, 3]); // Consume all values then check for done await finiteStream.drain(); await expect(Stream.empty()).emitsDone(); }); } ``` -------------------------------- ### Dart: Type-Safe Assertions with expect() Source: https://context7.com/invertase/spec/llms.txt Demonstrates the core `expect()` function in Spec for type-safe assertions in Dart. It covers equality, null, type, truthy/falsy, contains, length, and pattern matching checks. ```dart import 'package:spec/spec.dart'; void main() { test('basic assertions', () { var count = 42; // Equality checks expect(count).toEqual(42); // Structural equality expect(count).toBe(count); // Identity check (identical) expect(count).not.toEqual(0); // Negation with .not // Null checks String? name; expect(name).isNull(); expect(name).toBeNull(); // Alias for isNull() // Type checks Object value = Duration(seconds: 1); expect(value).isA(); // Truthy/Falsy checks expect(42).toBeTruthy(); expect(null).toBeFalsy(); expect(false).toBeFalsy(); // Contains checks (works on String, List, Map) expect('Hello world').toContain('Hello'); expect([1, 2, 3]).toContain(2); expect({'key': 'value'}).toContain('key'); // Length checks expect('Hello').toHaveLength(5); expect([1, 2]).toHaveLength(2); // Pattern matching expect('test@example.com').toMatch(RegExp(r'.*@.*\.com')); }); } ``` -------------------------------- ### Test Function Behavior with .throws and .returnsNormally() Source: https://context7.com/invertase/spec/llms.txt Verify function execution outcomes, ensuring they complete without errors or throw specific exceptions. This is crucial for testing error handling and expected function behavior. ```dart import 'package:spec/spec.dart'; void main() { test('function returns normally', () { int safeFunction() => 42; // Verify function completes without throwing expect(safeFunction).returnsNormally(); }); test('function throws', () { void throwsArgumentError() => throw ArgumentError('invalid'); void throwsStateError() => throw StateError('bad state'); void throwsCustom() => throw FormatException('parse error'); // Test specific exception types expect(throwsArgumentError).throws.isArgumentError(); expect(throwsStateError).throws.isStateError(); expect(throwsCustom).throws.isFormatException(); expect(throwsCustom).throws.isA(); }); test('function exception negation', () { void throwsError() => throw Error(); // Verify function does NOT throw a specific error type expect(throwsError).throws.not.isArgumentError(); }); } ``` -------------------------------- ### Dart Error Type Matchers Source: https://context7.com/invertase/spec/llms.txt Provides comprehensive matchers for verifying specific Dart error and exception types within tests. It requires the 'spec' package and is used to assert that a thrown exception matches an expected type. ```dart import 'package:spec/spec.dart'; void main() { test('error type matchers', () { // ArgumentError expect(() => throw ArgumentError('bad arg')).throws.isArgumentError(); // FormatException expect(() => throw FormatException('parse error')).throws.isFormatException(); // StateError expect(() => throw StateError('invalid state')).throws.isStateError(); // RangeError expect(() => throw RangeError('out of bounds')).throws.isRangeError(); // UnsupportedError expect(() => throw UnsupportedError('not supported')).throws.isUnsupportedError(); // UnimplementedError expect(() => throw UnimplementedError('TODO')).throws.isUnimplementedError(); // NoSuchMethodError expect(() => throw NoSuchMethodError.withInvocation(null, Invocation.getter(#foo))) .throws.isNoSuchMethodError(); // ConcurrentModificationError expect(() => throw ConcurrentModificationError()) .throws.isConcurrentModificationError(); // Generic Exception expect(() => throw Exception('generic')).throws.isException(); }); } ``` -------------------------------- ### Perform Numeric Comparisons with Specialized Matchers Source: https://context7.com/invertase/spec/llms.txt Utilize specialized matchers for precise numeric comparisons, including range checks, equality, and handling of special numeric values like NaN. Supports both positive and negative numbers, and zero. ```dart import 'package:spec/spec.dart'; void main() { test('numeric comparisons', () { expect(42).toEqual(42); expect(42).greaterThan(41); expect(42).greaterThanOrEqualTo(42); expect(42).lessThan(43); expect(42).lessThanOrEqualTo(42); // Negation expect(42).not.lessThan(40); }); test('numeric properties', () { expect(42).isPositive(); expect(-42).isNegative(); expect(0).isZero(); expect(double.nan).isNaN(); }); test('approximate equality', () { // Check if value is within delta of expected expect(3.14159).toBeCloseTo(3.14, 0.01); expect(100.5).toBeCloseTo(100, 1); }); } ``` -------------------------------- ### Assert List Contents and Membership Source: https://context7.com/invertase/spec/llms.txt Validate the contents of lists, checking for the presence of specific elements, ensuring all expected elements are included (regardless of order), and verifying the list's length. Supports negation for membership checks. ```dart import 'package:spec/spec.dart'; void main() { test('list contains', () { final numbers = [1, 2, 3, 4, 5]; expect(numbers).contains(3); expect(numbers).not.contains(10); expect(numbers).toHaveLength(5); }); test('list containsAll', () { final numbers = [1, 2, 3, 4, 5]; // Check that all expected values are present (any order) expect(numbers).containsAll([1, 3, 5]); expect(numbers).containsAll([5, 3, 1]); // Order doesn't matter expect(numbers).not.containsAll([1, 6, 7]); }); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.