【问题标题】:Angular 2.0.0 - Mocking ComponentsAngular 2.0.0 - 模拟组件
【发布时间】:2017-03-03 04:29:23
【问题描述】:

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

下面的示例代码。

table.component.html

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

table.component.ts

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

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

my-component.component.html

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

my-component.component.ts

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

export class MyComponent {
  @ViewChild('#mytable') mytable;

  myFunction() : void  {
    if(this.mytable.table.selection.length === 0){
       console.log();
    } else{
       console.log();
    }
  }

如何模拟它,以便我可以为 table.component.ts 中的 selection 设置值以在 table.component.ts 中进行测试strong>my-component.component.ts?

【问题讨论】:

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


    【解决方案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)]。当我们向selectionChange 发出一个值时,Angular 将相应地更改我们分配给它的属性。例如

    @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 value 的新事件。因为ParentComponent.value 绑定到selectionChange,Angular 会自动将其值更改为new value

    【讨论】:

    • 感谢您的回答。但是,我使用的是 primeNG 的数据表,而 p-datatable 组件是我无法控制的。另一方面,我如何模拟桌子?我是否在 testBed 中使用 overrideComponent?
    • 我刚刚给你看了。创建另一个组件作为模拟并将其添加到declarations,而不是使用 PrimeNg 的
    • 是的,我记得,但这是一项服务。尽管如此,我应该在 TestBed.configureTestingModule 或 TestBed.overrideComponent 中配置模拟表吗?
    • 不确定您在说什么服务。我的意思是我刚刚向您展示了上面的代码。你应该把它添加到 configureTestingModule 的声明中
    • 其实我没有导入 PrimeNg 的。这是一个笨蛋:plnkr.co/edit/tA104Zc8mUZpKKMxvmj3?p=catalogue
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 2021-08-18
    • 1970-01-01
    相关资源
    最近更新 更多