Search code examples
angulartestingangular-spectatorspectatorng-mocks

Angular component test with spectator logs "can't bind to input" warnings for mocked child component


I'm facing an issue mocking a child component in an Angular 9 component test using @ngneat/spectator. The mocking and passing of the mock work fine, but it throws warnings in the logs for the inputs (even though they are valid).

The simplified components look as follows:

@Component({
  selector: 'child',
  template: '<h2>{{someInput}}</h2>'
})
export class ChildComponent {
  @Input() someInput: string;
}

@Component({
  selector: 'parent',
  template: '<child [someInput]="inputVal"></child>'
})
export class ParentComponent {
  public inputVal = 'hello';
}

Now the spectator test

import { createComponentFactory, Spectator } from '@ngneat/spectator/jest';
import { MockComponent } from 'ng-mocks';
...

describe('ParentComponent', () => {
  let spectator: Spectator<ParentComponent>;
  let createComponent: SpectatorFactory<ParentComponent>;

  beforeEach(() => {
    createComponent = createComponentFactory({
      component: ParentComponent,
      declarations: [MockComponent(ChildComponent)]
    });

    spectator = createComponent();
  });

  describe('example', () => {
    it('should set the input', () => {
      expect(spectator.query(ChildComponent).someInput).toEqual('hello');
    });
  });

});

The test runs fine and passes. The logs, however, print warnings:

console.warn
    Can't bind to 'someInput' since it isn't a known property of 'child'.

Any ideas why it's logging a warning?


Solution

  • Found my own issue - turns out createComponentFactory() has to be called outside of the beforeEach().

    Once I moved it out of the beforeEach block the mocks started working as expected.