1

I am writing some component tests for my Nx Angular application using Cypress. I am trying to retrieve an instance of a provider that I set up in my test:

export const DASHBOARD_TOKEN = new InjectionToken<DashboardService>('Dashbaord');
let data: Project | undefined;
let dashboard: DashboardService;

before(function () {
    cy.fixture('project.json').then(function (json) {
        data = json;
    });
});
describe(ArrowChartComponent.name, () => {
    beforeEach(() => {
        TestBed.overrideComponent(ArrowChartComponent, {
            add: {
                imports: [ArrowChartModule],
                providers: [
                    { provide: DASHBOARD_TOKEN, useClass: DashboardService },
                    { provide: EVENT_SERVICE_TOKEN, useClass: EventService },
                ],
            },
        });
        dashboard = TestBed.inject(DASHBOARD_TOKEN);
    });

    it('renders', () => {
        cy.mount(ArrowChartComponent, {
            componentProperties: {
                id: 0,
                width: 0,
                height: 0,
                rebuild: false,
                showFastCreator: true,
            },
        });

    });
});

When I run the test, I get the following error:

"before each" hook for "renders":
     NullInjectorError: R3InjectorError(CompilerModule)[InjectionToken Dashbaord -> InjectionToken Dashbaord]: 
  NullInjectorError: No provider for InjectionToken Dashbaord!`

It is saying the there is no provider for my injection token, but above I clearly provide one. Why am I getting this error and how do I fix it?

afriedman111
  • 1,925
  • 4
  • 25
  • 42

1 Answers1

1

You can probably mock the factory behind your injection token:

TestBed.configureTestingModule({
    imports: [...],
    declarations: [...],
    providers: [
        {
            provide: DASHBOARD_TOKEN,
            useFactory: () => ({
                myMethodToMock: () => {},
            }),
        },
    ],
});
Wandrille
  • 6,267
  • 3
  • 20
  • 43