【问题标题】:How to mock directive on mock component如何在模拟组件上模拟指令
【发布时间】:2019-07-18 16:33:00
【问题描述】:

我正在对包含clarity 标记和clarit directives 的组件进行单元测试。

我已经模拟了清晰标签,但它们有指令clrDgItems,我不能用指令类模拟。

<clr-dg-row *clrDgItems="let item of items$ | async | filter : listFilter.keyword : ['trackingCode', 'title']" [clrDgItem]="episode">

我可以用ngFor 替换clrDgItems,但表格过滤器停止工作。

没有它,测试将无法编译:

无法绑定到“clrDgItemsOf”,因为它不是 'clr-dg-row'

当我将 mockDirective 添加为:我得到错误

失败:模块“DynamicTestModule”声明的意外值“[object Object]”

     function MockDirective(options: any): Directive {
         const metadata: Directive = {
         selector: options.selector,
         inputs: options.inputs,
         outputs: options.outputs
      };
      return new Directive(metadata);
    }

 TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        MockDirective({
          selector: '[clrDgItemsOf]',
        }),
      MockComponent({
      selector: 'clr-dg-row',
      template: '<ng-content></ng-content>',
      outputs: ['clrDgItemsOf'],
      inputs: ['clrDgItem']
    }), ...

有什么建议吗?

【问题讨论】:

    标签: angular unit-testing clarity


    【解决方案1】:

    您不使用CUSTOM_ELEMENTS_SCHEMA 的原因有哪些?你不需要模拟指令,因为它们会被忽略:

    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,    
      ],
      schemas: [
        CUSTOM_ELEMENTS_SCHEMA
      ]
    })
    

    如果你真的想模拟行为,你可以在你的规范文件中创建一个@Directive

    @Directive({
      selector: '[clrDgItems][clrDgItemsOf]'
    })
    export class MockClrDgItemsDirective {
      @Input()
      clrDgItemsOf: any;
    }
    

    并像往常一样将其添加到您的声明中:

    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        MockClrDgItemsDirective
      ]
    })
    

    甚至另一种选择是在 TestBed 的导入中导入 ClrDatagridModule

    【讨论】:

    • 我收到错误Property binding clrDgItemsOf not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations". ("mn [clrDgField]="'title'"&gt;Title&lt;/clr-dg-column&gt; &lt;clr-dg-column&gt;Comments&lt;/clr-dg-column&gt;
    • @shiva 如果您在规范中创建 MockClrDgItemsDirective 会怎样?
    • 确实有效!谢谢你。虽然我更喜欢模拟所有子组件。它给了我更多的灵活性,例如测试内部值...
    猜你喜欢
    • 2014-08-12
    • 1970-01-01
    • 2012-12-12
    • 2013-07-13
    • 2012-11-06
    • 1970-01-01
    • 2018-07-20
    • 2011-08-16
    • 2018-08-03
    相关资源
    最近更新 更多