簡體   English   中英

如何將值從Angular單元測試傳遞到動態HTML標簽

[英]How to pass value from Angular unit test into dynamic HTML tag

我想將單元測試中的"test"值傳遞給此動態HTML標記中的nodeNamenodeDisplayName ,以便顯示此復選框。

我的單元測試:

it('checkbox is appearing', () => {
        const nodes= [{
          nodeDisplayName: "test",
          nodeName: "test"
        }];
         //  pass value to HTML code

        const checkbox= fixture.debugElement.query((de) => {
          return de.nativeElement.id === 'test';
        });
        expect(checkbox).not.toBeNull();
});

我的HTML標記:

<div *ngFor="let node of nodes let i = index" class="multipleNodes">
    <label class="nodebtn bold" [id]=node.nodeName ngbTooltip="{{node.nodeDisplayName}}" tooltipClass="nodeTooltip">
         <input type="checkbox" attr.for="{{node}}" value="{{i}}" name="{{i}}" (change)="checkboxChange($event)">
                  {{node.nodeName}}
    </label>
</div>

期望HTML輸出(檢查):

<div class="multipleNodes">
      <label class="nodebtn bold active" tooltipClass="nodeTooltip" ng-reflect-tooltip-class="nodeTooltip" ng-reflect-ngb-tooltip="test" id="test">
            <input type="checkbox" for="[object Object]" value=0 name=0 >
                      " test "
      </label>
</div>

n.namen.displayName實際上來自上一頁,方法是單擊特定元素,然后發送到此頁面,但是我只想測試'test'元素。

我的.ts文件中的相關代碼段:

@Input() data;
 ngOnInit() {
if (this.data.process === 'click') {
        this.setLinear = true;
        this.nodes = this.data.nodes.map((n) => {
          return {
            nodeName: n.name,
            nodeDisplayName: n.displayName,
          };
        });
}

您可以模擬導入(我個人更喜歡),也可以在onInit完成后更新組件屬性。

重要的是要理解, ngOnInit()是在您的describe塊中的第一次ngOnInit() fixture.detectChanges()調用期間觸發的。

如果您使用第一種方法模擬導入,則需要確保在調用fixture.detectChanges之前完成此操作。 通常當由CLI生成的測試是有fixture.detectChanges的beforeEach循環回路內。 那將需要刪除,並且在每一個安裝完成后it您都需要顯式調用它。

輸入模擬:

it('checkbox is appearing', () => {
     const nodes = [{
              nodeDisplayName: "test",
              nodeName: "test"
            }]
     component.nodes = nodes; //in case nodes is public
     (component as any).nodes = nodes //in case nodes is private
     fixture.detectChanges();

     const checkbox= fixture.debugElement.query((de) => {
        return de.nativeElement.id === 'test';
     });
     expect(checkbox).not.toBeNull();
});

在onInit完成后進行更改(恕我直言,這不是最好的方法):

it('checkbox is appearing', () => {
     fixture.detectChanges();
     const data = {
          process: 'click',
          nodes: [{
              nodeDisplayName: "test",
              nodeName: "test"
            }]
         }
     component.data = data;
     fixture.detectChanges();

     const checkbox= fixture.debugElement.query((de) => {
        return de.nativeElement.id === 'test';
     });
     expect(checkbox).not.toBeNull();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM