1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

inject() must be called from an injection context in unit test

Discussão em 'Angular' iniciado por guiz, Junho 6, 2025.

  1. guiz

    guiz Guest

    When I am trying to use the AlertsComponent in my test file at the beginning, it require some services. After adding theses services, the following error appear:


    inject() must be called from an injection context​

    When I am using a class that doesn't use inheritance with a parent class, no provider is required and the test works fine, but when the test uses a component that requires a base class with services in its constructor, I have this error.

    AlertBase

    export abstract class AlertBase {
    constructor(protected alertService: IAlertService, protected alertResultService: IAlertResultService, protected paginationService: IPaginationService, protected selectedItemService: SelectedItemService) {
    }
    }


    AlertsComponent

    @Component({
    selector: 'alerts',
    templateUrl: './alerts.component.html',
    styleUrls: ['./alerts.component.less'],
    encapsulation: ViewEncapsulation.None,
    })

    export class AlertsComponent extends AlertBase implements OnInit, OnDestroy {


    constructor(
    private storageService: StorageProvider,
    protected alertServiceProvider: AlertServiceProvider,
    protected alertResultProvider: AlertResultProvider,
    private toastNotificationService: ToastNotificationService,
    protected selectedItemService: SelectedItemService,
    protected paginationService: PaginationServiceProvider, private modalService: ModalService) {
    super(alertServiceProvider, alertResultProvider, paginationService, selectedItemService);

    }
    }


    Test File :

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

    beforeEach(async () => {
    await TestBed.configureTestingModule({
    imports: [
    RouterTestingModule,
    //MockModule(NotificationModule)
    ],
    declarations: [AlertsComponent],
    providers: [
    MockProvider(StorageProvider),
    MockProvider(AlertServiceProvider),
    MockProvider(AlertResultProvider),
    ]
    })
    .compileComponents();
    });

    beforeEach(() => {
    fixture = TestBed.createComponent(AlertsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    });

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

    Continue reading...

Compartilhe esta Página