0

I have a constructor that uses this:

  constructor(
    public core: CoreComponent,
  ) {
   //
  }

But when i try to test these components with a testcase like this:

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        TestingModule.forRoot(),
      ]
    }).compileComponents();
  }));

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

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

I get a null injector error:

Error: StaticInjectorError(DynamicTestModule)[CoreSubMenuComponent -> CoreComponent]: 
  StaticInjectorError(Platform: core)[CoreSubMenuComponent -> CoreComponent]: 
    NullInjectorError: No provider for CoreComponent!

It is imported into the testingModule so that isn't the issue. I also tried adding it to the providers array. but that just moves it to the angular renderer which can't be added to the providers array. I also added an @injectable() tag before the @component tag in the CoreComponent but it doesn't change my tests failing.

I tried getting it with @host() but it throws an error. I also tried to get it with the Injector but that also throws an error. These are 4 components that use the CoreComponent as a var to get some info from them but they make the tests fail. All my other tests are pass just fine with over 80 tests. Just these 4 won't work because they try to get properties that are defined in the CoreComponent.

Does someone know how i could reference this component with an instance so that my tests will pass?

3
  • 2
    This may seem like a dumb question but is CoreComponent an actual component or a service? Commented Sep 4, 2018 at 16:07
  • Yess it's a component, it's actually the basecode of an ngprime template so you can look at it here: github.com/primefaces/primeng-blueprint/blob/master/src/app/… Commented Sep 5, 2018 at 7:42
  • I just called it all core instead of app because I handle other stuff in the app.component.ts Commented Sep 5, 2018 at 7:42

1 Answer 1

1

To fix this error use @host en @optional decorators. this tells the compiler to look for it but not require if it isn't provided:

  constructor(
    @Host() @Optional() public core: CoreComponent,
  ) {
    //
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.