【问题标题】:How to Access child component property in spec file as QueryList in Angular using @viewChildren如何使用 @viewChildren 在 Angular 中以 QueryList 的形式访问规范文件中的子组件属性
【发布时间】:2021-07-19 14:38:47
【问题描述】:

我在 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 的正确方法吗?请帮助解决此问题。

【问题讨论】:

    标签: angular unit-testing jasmine viewchildren


    【解决方案1】:

    要模拟你可以使用ng-mocks的东西。

    支持mock子组件,@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);
    });
    

    【讨论】:

    • 需要使用哪个版本的ng-mocks?我安装为 dev 依赖项并安装了 v8.1,但我无法导入 ngMocks,它说路径没有导出的成员“ngMocks”。从 'ng-mocks' 导入 { ngMocks };正在抛出错误。
    • @knbibin,你需要最新的,它支持所有Angular版本。
    • npm install ng-mocks 仅安装 v8.1。如果我尝试手动安装最新版本 12.3.1,它会说 No matching version found for ng-mocks@12.3.1
    • 非常有趣。您有注册表镜像或代理吗?你也可以试试ng-mocks@^12.0.0吗?
    • 我尝试了所有选项。为什么它在 v8.1 中抛出导入错误?
    猜你喜欢
    • 2019-09-08
    • 2018-11-23
    • 2020-01-03
    • 2018-11-28
    • 1970-01-01
    • 2019-11-23
    • 2019-06-30
    • 2020-06-18
    • 2019-06-06
    相关资源
    最近更新 更多