Angular 2.0.0 - Mocking Components

2019-07-27 14:12发布

问题:

How do you mock a component in Angular 2.0.0 Final Release? I have a problem in mocking a component that has a variable that I use for logic in another component. Specifically, I want to mock a PrimeNG Datatable selection.

Sample code below.

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();
    }
  }

How do I mock it so that I can set values to the selection in the table.component.ts to test in the my-component.component.ts?

回答1:

The banana-box [()] syntax is just shorthand for [] (), where the name of the output () is just the name of the input [], suffixed with Change. For example

import { Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'p-datatable',
  template: `...`
})
class MockDataTable {
  @Input() value;

  @Input() selection;
  @Output() selectionChange = new EventEmitter();
}

Here the output selectionChange is the same name as the input selection, just suffixed with Change. Now we can use the syntax [(selection)]. When we emit a value to the selectionChange, Angular will change the property that we assign to it accordingly. For example

@Component({
  template: '<p-datatable [(selection)]="value"></p-datatable>
})
class ParentComponent {
  value = somevalue;
}

class MockDataTable {
  @Output() selectionChange = new EventEmitter();

  click() {
    this.selectionChange('new value');
  }
}

Here, when click is called on the data table, it emits a new event with the value new value. Because the ParentComponent.value is bound to the selectionChange, Angular will automatically change its value to new value.