我正在尝试测试我的 Angular 2 组件,使用 new MyComponent()
进行实例化。但是,对于采用 @Input
的组件,我该如何传递它们?然后,如果实例化,说我想更改输入。这只是重新分配给我传入的变量的问题吗?
最佳答案
如果您使用 new
创建一个实例,则您无法执行任何其他操作来分配给该字段。您可以使用 TestComponentBuilder
进行更改检测和绑定(bind)。
下面是测试 BwuArraySelector
组件的 Dart 代码示例。
我假设您可以弄清楚如何在 TS 中执行此操作。
/// Component only for testing BwuArraySelector
@Component(
selector: 'test-cmp-singleconfigured',
directives: const [BwuArraySelector],
template: '''
<bwu-array-selector #singleConfigured
[items]='[{"name": "one"},{"name": "two"},{"name": "three"}]'>
</bwu-array-selector>
''')
class SingleConfigured {
@ViewChild('singleConfigured') BwuArraySelector arraySelector;
}
...
// inject the TextComponentBuilder and create a component instance
ngTest('single selection', (TestComponentBuilder tcb) async {
ComponentFixture tc = await tcb.createAsync(SingleConfigured);
tc..detectChanges();
BwuArraySelector el =
(tc.componentInstance as SingleConfigured).arraySelector;
调用 detectChanges()
使用来自 SingleConfigured
测试组件模板绑定(bind)的值初始化 BwuArraySelector
的输入。
关于angular - 使用@Input 测试 Angular 2 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34670144/