Reputation: 13622
I heard that I can test services on the Dart VM (so without browser). I'm wondering how I can do this.
So say I want to test this service:
@Injectable()
class MyService {
String greet = 'Hello world';
}
I could test just like this:
import 'package:test/test.dart';
void main() {
var myService = new MyService();
test('test greet', () {
expect(myService, equals('Hello World'));
});
}
So this example is very simple, but for more complex service classes, I would like to use angular 2 dependency injection. How could I do this?
Upvotes: 1
Views: 414
Reputation: 3189
To test pure injectable services (i.e. not components) all you need is create an injector that contains dependencies (usually mocks) for the tested class. Here is an example:
import 'package:test/test.dart';
import 'package:angular2/angular2.dart';
import 'package:angular2/src/core/reflection/reflection_capabilities.dart';
@Injectable()
class Foo {
greet() => 'hi';
}
@Injectable()
class Bar {
final Foo foo;
Bar(this.foo);
}
class MockFoo implements Foo {
greet() => 'bonjour';
}
main() {
reflector.reflectionCapabilities = new ReflectionCapabilities();
group('MyService', () {
Injector inj;
setUp(() {
inj = Injector.resolveAndCreate([Bar, provide(Foo, useClass: MockFoo)]);
});
test('should work', () {
Bar testSubject = inj.get(Bar);
expect(testSubject.foo.greet(), 'bonjour');
});
});
}
Upvotes: 3