Component Testing: Basics (DRAFT) 4.0

If you notice any issues with this page, please report them.

Ready to write tests for your own project? This page explains how to setup your project, and it illustrates how to write basic component tests.

Pubspec configuration

Projects with component tests depend on the angular_test and test packages. Because these packages are used only during development, and not shipped with the app, they don’t belong under dependencies in the pubspec. Instead, test and angular_test are under dev_dependencies, for example:

toh-0/pubspec.yaml (dev_dependencies)

dev_dependencies: angular_test: ^1.0.0 browser: ^0.10.0 dart_to_js_script_rewriter: ^1.0.1 test: ^0.12.30

The pubspec.yaml file should also include the pub_serve transformer, and list test files as Angular entry_points. Without these changes, angular_test-based tests won’t run.

toh-0/pubspec.yaml (transformers)

transformers: - angular: entry_points: - web/main.dart - test/**_test.dart - test/pub_serve: $include: test/**_test.dart - dart_to_js_script_rewriter

API basics: test() and expect()

Write component tests using the test package API. For example, define tests using test() functions containing expect() test assertions:

toh-0/test/app_test.dart (simple test)

test('Default greeting', () { expect(fixture.text, 'Hello Angular'); });

You can also use other test package features, like group(), to write your component tests.

Test fixture, setup and teardown

Component tests must explicitly define the component under test. You define it by passing the component class name as a generic type argument to the NgTestBed and NgTestFixture classes:

toh-0/test/app_test.dart (test bed and fixture)

final testBed = new NgTestBed<AppComponent>(); NgTestFixture<AppComponent> fixture;

You’ll generally initialize the fixture in a setUp() function. Since component tests are often asynchronous, the tearDown() function generally instructs the test framework to dispose of any running tests before it moves on to the next test group, if any. Here is an example:

toh-0/test/app_test.dart (excerpt)

@Tags(const ['aot']) @TestOn('browser') // ··· @AngularEntrypoint() void main() { final testBed = new NgTestBed<AppComponent>(); NgTestFixture<AppComponent> fixture; setUp(() async { fixture = await testBed.create(); }); tearDown(disposeAnyRunningTest); test('Default greeting', () { expect(fixture.text, 'Hello Angular'); }); // ··· }

Use setUpAll() and tearDownAll() for setup/teardown that should encompass all tests and be performed only once for the entire test suite.

More package:test features

You’ve just worked through the elementary features of package:test. For complete coverage of the package capabilities, see the package documentation.