Search code examples
angularunit-testingclarity

How to mock directive on mock component


I'm unit testing a component which contains clarity tags with clarit directives.

I have mocked out the clarity tags but they have directives clrDgItems which I can't mock with directive class.

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

I could replace clrDgItems with ngFor but the table filter stops working.

Without it the test does not compile :

Can't bind to 'clrDgItemsOf' since it isn't a known property of 'clr-dg-row'

When I add mockDirective as: I get error

Failed: Unexpected value '[object Object]' declared by the module 'DynamicTestModule'

     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']
    }), ...

Any suggestions?


Solution

  • Any reason why you are not using the CUSTOM_ELEMENTS_SCHEMA? You don't need to mock directives then, as those are simply ignored:

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

    If you really want to mock behaviour, you can just create a @Directive inside your spec file:

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

    and add it to your declarations like normally:

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

    Even another option is to just import the ClrDatagridModule in the imports of your TestBed