如何解决如何使用@viewChildren 在 Angular 中以 QueryList 的形式访问规范文件中的子组件属性
我在 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: {},_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://ng-mocks.sudo.eu/guides/view-child等
所以你可以尝试这样的事情:
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);
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。