Angular 2.0.0 - 模拟组件

时间:2016-10-21 01:14:06

标签: unit-testing angular mocking karma-jasmine primeng

如何在Angular 2.0.0 Final Release中模拟组件?我在模拟一个组件时遇到了问题,该组件具有我在另一个组件中用于逻辑的变量。具体来说,我想模拟 PrimeNG Datatable 选择。

以下示例代码。

table.component.html

this

table.component.ts

        <p-dataTable
          #table
          [value]="myDatasource"
          [(selection)]="mySelections"
          ...
        >

我-component.component.html

@Component({
  selector: 'my-table',
  templateUrl: './table.component.html'
})

export class TableComponent{
    @ViewChild('table') datatable;

我-component.component.ts

<my-table #mytable></my-table>

如何模拟它以便我可以将值设置为 table.component.ts 中的 选择 以在 MY-component.component.ts

1 个答案:

答案 0 :(得分:1)

香蕉盒[()]语法只是[] ()的简写,其中输出()的名称只是输入[]的名称,后缀为{ {1}}。例如

Change

此处输出import { Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'p-datatable', template: `...` }) class MockDataTable { @Input() value; @Input() selection; @Output() selectionChange = new EventEmitter(); } 与输入selectionChange的名称相同,后缀为selection。现在我们可以使用语法Change。当我们向[(selection)]发出一个值时,Angular将相应地更改我们分配给它的属性。例如

selectionChange

此处,在数据表上调用@Component({ template: '<p-datatable [(selection)]="value"></p-datatable> }) class ParentComponent { value = somevalue; } class MockDataTable { @Output() selectionChange = new EventEmitter(); click() { this.selectionChange('new value'); } } 时,它会发出值为click的新事件。由于new valueParentComponent.value绑定,因此Angular会自动将其值更改为selectionChange