簡體   English   中英

Angular 5:如何為數據綁定屬性編寫 Jasmine 單元測試

[英]Angular 5 : How to write a Jasmine unit test for a data binding attribute

要求:我需要為HTML elementdata-binding屬性編寫單元測試。

這是代碼

<kendo-grid
            [kendoGridBinding]="gridData"
            [resizable]="true"
            style="height: 300px">
            <kendo-grid-column
                field="UnitPrice"
                title="Unit Price"
                [width]="180"
                filter="numeric"
                format="{0:c}">
            </kendo-grid-column>
</kendo-grid> 

我需要為resizable屬性值編寫單元測試。

到目前為止我嘗試過的:

  it('kendo-grid element should contain resizable attribute with "true" value', () => {
    const element = fixture.debugElement.nativeElement.querySelector('kendo-grid');
    expect(element.resizable).toBeTruthy();
  });

運行 Karma 測試運行程序時失敗。

在此處輸入圖片說明

任何幫助將是非常可觀的。

這些屬性在瀏覽器中轉換為 ng-reflect-{attributeName} ,因此 jasmine 需要查找該屬性。 下面的測試應該可以工作。

 it('kendo-grid element should contain resizable attribute with "true" value', () => {
    const element = fixture.debugElement.query(By.css('kendo-grid'));
    expect(element.nativeElement.getAttribute('ng-reflect-resizable')).toBe('true');
  });

到今天為止,還有一個陷阱。 我發現了一些討論,人們在那里抱怨這個屬性。 帕維爾·科茲洛夫斯基

我認為任何人都不應該真正使用 ng-reflect-... 來處理任何“嚴重”的事情,因為這些東西只是調試模式,不會在生產版本中使用。

據我了解, kendo-grid是第 3 方組件。 在這種情況下,您不應該對其進行真正的測試,您只需要集成測試來檢查它是否正確實現。 所以,你不應該包括kendo組件到您的測試床的配置,並設置NO_ERRORS_SCHEMA

我一直在做這樣的事情。 能不能試一次。

const element = fixture.debugElement.query(By.css('kendo-grid'));
expect(element.nativeElement.resizable).toBeTruthy();

您必須在TestBed架構中添加NO_ERRORS_SCHEMA

import { NO_ERRORS_SCHEMA } from '@angular/core';
...
describe('HelloComponent', () => {
  ...
  TestBed.configureTestingModule({
    schemas: [NO_ERRORS_SCHEMA],
    declarations: [ ... ]
  });
  ...
});

這允許在單元測試組件時忽略所有子組件。 所以你的單元測試不會失敗。

您可以在stackblitz演示中查看此示例。

暫無
暫無

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

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