Angular Unit Test Error: 1 component threw errors during cleanup at...

Discussão em 'Angular' iniciado por denisiulian, Março 26, 2025.

  1. denisiulian

    denisiulian Guest

    I'm testing a component which has injected a service. The problem that as I saw, it's not entering the ngOnDestroy(). I ask explicity the test to destroy() after every test I get error message that "cannot unsubscribe from undefined". What could be the problem?

    Component:

    //...
    subscription: Subscription;

    constructor(private readonly router: Router,
    private dialog: MatDialog,
    private readonly carService: carService) {
    }

    ngOnInit(): void {
    this.cars$ = this.carService.getCars();
    this.subscription= this.cars$.subscribe(cars=> {
    this.cars= cars;
    });
    }

    ngOnDestroy() {
    this.subscription.unsubscribe();
    }


    Test:

    //...
    beforeEach(async () => {
    await TestBed.configureTestingModule({

    providers: [
    {provide: MatDialog, useClass: dialogMock},
    {provide: Router, useValue: routerMock},
    {provide: APP_BASE_HREF, useValue: '/cars'}
    ]
    }).compileComponents();

    component = TestBed.createComponent(CarComponent).componentInstance;
    service = TestBed.inject(CarService);
    service.setProjects([firstCar, secondCar]);
    component.ngOnInit();
    });

    it('test', () => {
    expect(component).toBeInstanceOf(CarComponent);
    });

    Continue reading...

Compartilhe esta Página