Search code examples
angularangular-directiveangular-test

Angular testing component with mocked structural directive fails


I am trying to mock structural directive in a component test but Im getting error.

Following test is failing with a message:

Property binding appSome 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". ("[ERROR ->]TEST

I am mocking structural directive SomeDirective with SomeMockDirective defined within app.component.spec.ts. Test is failing.

If I switch declarations so that it contains SomeDirective instead - the test passes.

I im wondering why I can not make it working with mocked version.

Template:

<h1 *appSome="true">TEST</h1>

Directive (kind of production :) ):

@Directive({
  selector: '[appSome]'
})
export class SomeDirective implements OnDestroy {
  show: boolean;
  ...
}


Test:

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { Directive, NO_ERRORS_SCHEMA } from '@angular/core';

@Directive({
  selector: '[appSome]'
})
export class SomeMockDirective {}

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent, SomeMockDirective], // test is failing, switch the directive to SomeDirective and it passes
      schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  });
});

Reproduction repo: https://github.com/felikf/angular-test-directive

git clone https://github.com/felikf/angular-test-directive.git 
npm i
ng test

My question is, why the mocked version does not work, even if the mocked version is provided in providers: [] and the directive has the same selector.


Solution

  • The mocked version doesn't work because you haven't defined appSome input property:

    @Directive({
      selector: '[appSome]'
    })
    export class SomeMockDirective {
      @Input() appSome;  <================= add this
    }