Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing Angular 9 Component with @Host parameter can't resolve parameters

This spec gives me a

"Error: Can't resolve all parameters for FooComponent: (?)."

error and I can't see why. Any help on this would be appreciated.

foo.component.ts

import {Component, Host } from '@angular/core';
import {BarComponent} from './bar.component';

@Component({
    selector: 'foo',
    template: `<div>foo</div>`
})
export class FooComponent {
    constructor(@Host() private barComponent: BarComponent) {
        // do something with bar
    }
}

bar.comonent.ts

import {Component, Injectable} from '@angular/core';

@Component({
    selector: 'bar',
    template: `<div>bar<foo/></div>`
})
@Injectable()
export class BarComponent { }

foo.component.spec.ts

import {TestBed, async, ComponentFixture} from '@angular/core/testing';
import {FooComponent} from './foo.component';
import {BarComponent} from './bar.component';

describe('FooComponent', () => {
    let component: FooComponent;
    let fixture: ComponentFixture<FooComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [
                FooComponent,
            ],
            providers: [
                BarComponent
            ],
        });
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(FooComponent);
        component = fixture.componentInstance;
    });

    it('should compile', () => {
        expect(component).toBeTruthy();
    });
});
like image 529
GruffT Avatar asked Aug 13 '26 06:08

GruffT


1 Answers

Maybe overrideComponent method of configureTestingModule will help:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        FooComponent,
      ]
    }).overrideComponent(FooComponent, {
      add: {
        providers: [
          { provide: BarComponent }
        ]
      }
    });
  }));
like image 129
Reza Avatar answered Aug 15 '26 22:08

Reza