![](/img/trans.png)
[英]Verify that a component with data binding is created | Angular | Jasmine | Unit Test
[英]Angular 5 : How to write a Jasmine unit test for a data binding attribute
要求:我需要為HTML element
的data-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.