Search code examples
angularunit-testingjasminekarma-jasmineangular-cdk

There is no directive with "exportAs" set to "cdkStep"


I get this error from karma/jasmin in my spec.ts:

There is no directive with "exportAs" set to "cdkStep"

<!-- Step 1 -->
<cdk-step [ERROR ->]#step1="cdkStep">
    <ng-template cdkStepLabel>
        <div class="step-content">
<!-- Step 2 -->
<cdk-step [ERROR ->]#step2="cdkStep">
    <ng-template cdkStepLabel>
        <div class="step-content">
<!-- Step 3 -->
<cdk-step [ERROR ->]#step3="cdkStep">
    <ng-template cdkStepLabel>
        <div class="step-content">
<!-- Step 4 -->

And I have this declared in my component:

@ViewChild('step1') private step1: CdkStep;
@ViewChild('step2') private step2: CdkStep;

And this is the TestBed config:

    TestBed.configureTestingModule({
        declarations: [ StepsComponent ],
        schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();

Overall, my code is very similar to this Stackblitz example:
https://stackblitz.com/edit/angular-cdk-stepper-demo

I am aware that this question has already been asked multiple times here on SO, but none of them regarding 'cdkStep'.
Anyone got an idea what I have been missing? The component works fine - it's just that I can't get a simple expect(component).toBeTruthy(); get to succeed.


Solution

  • Your component depends on the cdk-step component, which would be available in your TestBed once you import the CdkStepperModule into it.

    Because this isnt the case, angular does not create an instance of CdkStep whenever it encounters the cdk-step tag as the association is not registered. Consequentially, you wont be able to bind those template variables to an instance of CdkStep, as such instances simply dont exist.

    Normally angular would complain whenever it encounters unknown/custom tags by throwing the typical some-component is not an angular component, but because you are using the CUSTOM_ELEMENTS_SCHEMA this check is skipped.

    In order to register the CdkStep with the cdk-step selector, you need to refactor your setup into:

    import { CdkStepperModule} from '@angular/cdk/stepper';
    ...
    TestBed.configureTestingModule({
        imports: [CdkStepperModule],
        declarations: [StepsComponent]
    }).compileComponents();