[英]How to Access child component property in spec file as QueryList in Angular using @viewChildren
我在 parent.component.ts 文件中有以下代碼,我在其中使用 @ViewChildren 作為 QueryList 訪問子網格。
@ViewChildren(ChildComponent) childComponent: QueryList<any>;
我在訪問 childComponent 屬性的組件中具有以下功能。
checkProperty() {
let isNewRow = this.childComponent[_results].some(
item => item.newRowCreated === true
)
if(isNewRow) {
this.newRowEnabled = true;
}
}
在為 checkProperty() 方法編寫 jasmine 測試時,我為此創建的模擬數據拋出錯誤,我無法測試此方法。 請找到測試用例代碼。
it('test checkProperty() method', () => {
component.childComponent = {
changes: {},
first: {},
last: {},
length: 1,
dirty: false,
_results: [{newRowCreated: true}]
}
fixture.detectChanges();
component.checkProperty();
expect(component.newRowEnabled).toBe(true);
});
此代碼在規范文件中模擬 childComponent 的位置拋出錯誤。 我收到以下錯誤。
Type 'changes: {},first: {},last: {},length: 1,dirty: false,_results: [{newRowCreated: true}' is missing the following properties form type QueryList<any>: map,filter, find, reduce and 7 more.
這是將 childComponent 模擬為 QueryList 的正確方法嗎? 請幫助解決這個問題。
要模擬事物,您可以使用ng-mocks 。
它支持模擬子組件, @ViewChildren
: https : @ViewChildren
等。
所以你可以嘗試這樣的事情:
beforeEach(() => TestBed.configureTestingModule({
declarations: [
ParentComponent,
// Mocking the child component
MockComponent(ChildComponent),
],
}));
it('test checkProperty() method', () => {
// changing properties of the child component
ngMocks.findInstance(ChildComponent).newRowCreated = true;
// triggers and assertions
fixture.detectChanges();
component.checkProperty();
expect(component.newRowEnabled).toBe(true);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.