Cannot access 'Component' before initialization. Circular dependency in Jasmine testing....

Discussão em 'Angular' iniciado por Darío Ojeda Jurado, Março 14, 2025.

  1. In the example below, after running ng test --include my-component.component.spec.ts, I'm getting this error:


    An error was thrown in afterAll Uncaught ReferenceError: Cannot access 'MyComponentComponent' before initialization
    ​

    I think this is due to a circular dependency, because my component access a route file where the component itself is referenced.

    my-component.component.ts

    import {Component, OnInit} from '@angular/core';
    import {myRoutes} from './my-routes';

    @Component({
    selector: 'mi-component',
    template: ``,
    })
    export class MyComponentComponent implements OnInit {
    ngOnInit(): void {

    }

    routesModification() {
    const routes = myRoutes;
    routes[0].path = '/new-route';
    }
    }


    my-component.component.spec.ts

    import {ComponentFixture, TestBed} from '@angular/core/testing';
    import {MyComponentComponent} from './my-component.component';

    describe('MyComponentComponent class', () => {
    let component: MyComponentComponent;
    let fixture: ComponentFixture<MyComponentComponent>;
    beforeEach(async () => {
    await TestBed.configureTestingModule({
    declarations: [MyComponentComponent],
    imports: [],
    providers: [],
    }).compileComponents();

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

    it('El componente deberia estar creado correctamente', () => {
    expect(component).toBeTruthy();
    });
    });


    my-routes.ts

    import {Routes} from '@angular/router';
    import {MyComponentComponent} from './my-component.component';

    export const myRoutes: Routes = [
    {
    path: '',
    component: MyComponentComponent,
    },
    ];


    I need to fix this so that the test passes without touching the component or the route files, which I am not allowed. This is a problem that occurs only when I launch the test individually, when I launch the application or when I launch ng test globally, no such message appears.

    Continue reading...

Compartilhe esta Página