我目前正在将Angular 4.0 Dart 1.x应用程序移植到Angular 5.2 Dart 2.1。 大部分都可以正常工作,但是我很难使组件测试正常工作。
下面是我移植的一些代码,问题是我需要一个模拟类,该类的字段.action也是一个模拟类。因此,我使用when(mockRegattaStore.action).thenReturn(mockRegattaActionHelper);
如果此后我直接访问mockRegattaStore.action字段,那么它将给我模拟实例。但是,如果我的组件在其构造函数中对其进行访问,则它将返回null。好像注入器为我提供了一个模拟RegattaStore的新实例。然后,我尝试打印mockRegattaStore的hashCode,但它似乎始终为0。
这里有指向原始工作测试https://github.com/sturmf/regatta-angular2/blob/master/frontend/test/event_list_test.dart
的链接这里是端口https://github.com/sturmf/regatta-angular2/blob/port_to_dart_2.1/frontend/test/event_list_test.dart
[...imports left out...]
@GenerateInjector([
ClassProvider(Router, useClass: MockRouter),
ClassProvider(RegattaStore, useClass: MockRegattaStore),
ClassProvider(RegattaActionHelper, useClass: MockRegattaActionHelper),
])
final InjectorFactory rootInjector = self.rootInjector$Injector;
void main() {
final injector = InjectorProbe(rootInjector);
final testBed = NgTestBed.forComponent<EventListComponent>(ng.EventListComponentNgFactory, rootInjector: injector.factory);
NgTestFixture<EventListComponent> fixture;
EventListComponentPO testPO;
tearDown(disposeAnyRunningTest);
test('EventListComponent list contains dummy event', () async {
final mockRegattaStore = injector.get<MockRegattaStore>(RegattaStore);
final mockRegattaActionHelper = injector.get<MockRegattaActionHelper>(RegattaActionHelper);
when(mockRegattaStore.state.events)
.thenReturn({'-K2ib4H77rj0LYewF7dP': new Event('-K2ib4H77rj0LYewF7dP', 'Dummy Event')});
when(mockRegattaStore.state.eventList).thenReturn(['-K2ib4H77rj0LYewF7dP']);
when(mockRegattaStore.action).thenReturn(mockRegattaActionHelper);
fixture = await testBed.create();
final context = HtmlPageLoaderElement.createFromElement(fixture.rootElement);
testPO = EventListComponentPO.create(context);
final items = testPO.items;
expect(items, hasLength(1));
final element = items[0].getElementsByCss('.event-item-name').first;
expect(element.visibleText, equals('Dummy Event'));
});
}
此外,我还将英雄示例中的utils.dart文件用于InjectorProbe。