Component Testing: Basics (DRAFT) 6.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, build_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 add them under dev_dependencies, for example:

toh-0/pubspec.yaml (dev_dependencies)

dev_dependencies:
  ngtest: ^4.1.1
  build_runner: ^2.2.0
  build_test: ^2.1.5
  build_web_compilers: ^3.2.4
  test: ^1.21.0

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)

import 'package:angular_tour_of_heroes/app_component.template.dart' as ng;
// ···
void main() {
  final testBed = NgTestBed<AppComponent>(ng.AppComponentNgFactory);
  late 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)

@TestOn('browser')

import 'package:ngtest/ngtest.dart';
import 'package:angular_tour_of_heroes/app_component.dart';
import 'package:angular_tour_of_heroes/app_component.template.dart' as ng;
import 'package:test/test.dart';

void main() {
  final testBed = NgTestBed<AppComponent>(ng.AppComponentNgFactory);
  late 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 test documentation.