最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot access 'Component' before initialization. Circular dependency in Jasmine testing. Angular 17

programmeradmin5浏览0评论

In the example below, after running ng test --include my-componentponent.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-componentponent.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-componentponent.spec.ts

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

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

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

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

my-routes.ts

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

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.

In the example below, after running ng test --include my-componentponent.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-componentponent.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-componentponent.spec.ts

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

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

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

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

my-routes.ts

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

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.

Share Improve this question asked Mar 14 at 7:57 Darío Ojeda JuradoDarío Ojeda Jurado 8811 bronze badges 2
  • please replicate the error in stackblitz and update on the question. – Naren Murali Commented Mar 14 at 8:04
  • @NarenMurali I replicated it in stackblitz and it doesn't fail. Is just like when I launch the ng test command. But I need to launch the test individually with ng test --include my-component.spec.ts. That's when it fails. – Darío Ojeda Jurado Commented Mar 14 at 8:28
Add a comment  | 

1 Answer 1

Reset to default 1

Without Modifying component:

We create a dummy component assign it to the default route, to bypass this error message, you can revert it to the original component on the beforeEach or afterAll, but the bottom solution is the proper one I feel.

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponentComponent } from './my-componentponent';
import { myRoutes } from './my-routes';
import { Component } from '@angular/core';

@Component({
  selector: 'dummy',
})
export class DummyComponent {}

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

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

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

Modifying the component:

I think you have accessed routes which already contains the same component (import {myRoutes} from './my-routes';) you are accessing it before it is defined (export class MyComponentComponent implements OnInit {).

Instead try to access the routes through the router config property, then update the routes, finally use resetConfig to apply the routes again.

import { Component, inject, OnInit } from '@angular/core';
import { Router } from '@angular/router';

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

  routesModification() {
    const routes = this.router.config;    // <- changed here!
    routes[0].path = '/new-route';        // <- changed here!
    this.router.resetConfig(routes);      // <- changed here!
  }
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论