Unit testing for custom toolbar components in Jasmine - No provider for NavigationService!

0 Answers 194 Views
ToolBar
Ben
Top achievements
Rank 1
Ben asked on 09 Mar 2023, 08:05 PM

Hello,

I'm trying to write a custom ToolBar ToolComponent with unit tests - using Angular 15.2.1 with jasmine.

My simplified component code:

import { Component, ElementRef, forwardRef, Input, TemplateRef, ViewChild } from '@angular/core';
import { ToolBarComponent, ToolBarToolComponent } from '@progress/kendo-angular-toolbar';

@Component({
  template: `
    <ng-template #toolbarTemplate>
      <span #toolbarElement>
        <h4>{{ text }}</h4>
      </span>
    </ng-template>
  `,
  providers: [{ provide: ToolBarToolComponent, useExisting: forwardRef(() => ToolbarTitleComponent) }]
})
export class ToolbarTitleComponent extends ToolBarComponent {
  @Input() text = '';
  @ViewChild('toolbarTemplate', { static: true })
  public toolbarTemplate!: TemplateRef<unknown>;
  @ViewChild('toolbarElement', { static: false })
  public toolbarElement!: ElementRef;
}

with corresponding .spec file

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { LocalizationService } from '@progress/kendo-angular-l10n';
import { RefreshService, ToolBarModule } from '@progress/kendo-angular-toolbar';

import { ToolbarTitleComponent } from './toolbar-title.component';

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

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ToolbarTitleComponent],
      providers: [
        { provide: LocalizationService, useValue: LocalizationService },
        { provide: RefreshService, useValue: RefreshService }
        // { provide: NavigationService, useValue: NavigationService } // <--- this doesn't work, even when trying to use a spy object
      ],
      imports: [ToolBarModule]
    }).compileComponents();

    fixture = TestBed.createComponent(ToolbarTitleComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

When trying to run the test, I get the following error (which is expected, since I'm not providing the navigation service in the spec):

NullInjectorError: R3InjectorError(DynamicTestModule)[NavigationService -> NavigationService]: 
  NullInjectorError: No provider for NavigationService!

Unfortunately, the NavigationService does not seem to be exported from the package definition so I don't think there's an injection token being generated by Angular, and I cannot figure out how to properly provide the NavigationService to the TestBed so my test can run without bombing.

Is there a way to do this to enable me to test these types of components?

No answers yet. Maybe you can help?

Tags
ToolBar
Asked by
Ben
Top achievements
Rank 1
Share this question
or