如何在 Dart 虚拟机上测试 angular 2 个服务?
How to test angular 2 services on the Dart VM?
我听说我可以在 Dart VM 上测试服务(所以没有浏览器)。我想知道我该怎么做。
假设我想测试这个服务:
@Injectable()
class MyService {
String greet = 'Hello world';
}
我可以这样测试:
import 'package:test/test.dart';
void main() {
var myService = new MyService();
test('test greet', () {
expect(myService, equals('Hello World'));
});
}
所以这个例子很简单,但是对于更复杂的服务类,我想使用angular 2依赖注入。我该怎么做?
要测试纯可注入服务(即不是组件),您只需要创建一个注入器,其中包含用于测试的依赖项(通常是模拟)class。这是一个例子:
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');
});
});
}
我听说我可以在 Dart VM 上测试服务(所以没有浏览器)。我想知道我该怎么做。
假设我想测试这个服务:
@Injectable()
class MyService {
String greet = 'Hello world';
}
我可以这样测试:
import 'package:test/test.dart';
void main() {
var myService = new MyService();
test('test greet', () {
expect(myService, equals('Hello World'));
});
}
所以这个例子很简单,但是对于更复杂的服务类,我想使用angular 2依赖注入。我该怎么做?
要测试纯可注入服务(即不是组件),您只需要创建一个注入器,其中包含用于测试的依赖项(通常是模拟)class。这是一个例子:
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');
});
});
}