DebugElement.Nativelement未定义

时间:2019-05-01 18:19:47

标签: angular unit-testing jasmine

我是单元测试角度应用程序的新手。我已经初始化component.ts变量record.products,record是Records类型。我想进行单元测试,如果单击删除按钮是否调用了删除功能。并且只有在初始化此记录变量后,此删除才会出现在DOM中。我给出了对应于这些变量的代码片段。

Template.html

<tr *ngFor="let product of record.products; let i = index ">
 <td>
   <button (click)="delete(i)" class="btn1">Delete</button>
 </td>
as you see only if record.product is populated delete button will appear in DOM

Component.ts

record : Record; //Record class is below
 productForm: FormGroup;

products = [
    {
      name:'New Product'
    }]

productTemplate = {
    productid : '1',
    productname:'xyz'

  }


ngOnInit() {

    this.productForm = this.form.group({
      productControl: this.products
    });

    this.record['products'] = [];
    this.addProduct();
  }

  addProduct() {
    let product = JSON.parse(JSON.stringify(this.productTemplate));
    product.id  = 'ent-' + UUID.UUID();
    this.record['products'].push(product);
  }

  deleteProduct(i) {
    this.record['products'].splice(i,1);
  }

Record.ts

export class Entitlement {
    id: string;
    products:any;
}

myspec.ts

 it('should delete added product by clicking on delete button',()=>{

let mockRecordData:Record;
component.record=mockRecordData; 

// also tried
mockRecordData.products="some data";
component.record=mockRecordData; 
let buttons=fixture.debugElement.queryAll(By.css('.btn')).nativeElement;// gives error 

console.log(component.record['products']); 
//expected to print some data but gives only error
})

1 个答案:

答案 0 :(得分:0)

嗨,我通过更改获得了访问DOM元素删除按钮

record:记录;记录:任何;

通过更改变量的数据类型很简单的问题就解决了!!!