inject() 必须从单元测试中的注入上下文中调用

问题描述 投票:0回答:1

当我一开始尝试在测试文件中使用 AlertsComponent 时,它需要一些服务。添加这些服务后出现以下错误:

inject() 必须从注入上下文调用

当我使用的类不使用父类的继承时,不需要提供程序并且测试工作正常,但是当测试使用需要基类和构造函数中的服务的组件时,我会遇到此错误。

警报库

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

警报组件

@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);

  }
}

测试文件

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();
  });
});
angular angularjs jasmine karma-jasmine karma-runner
1个回答
0
投票

将您的

AlertsComponent
切换为
standalone: true
并尝试以下操作:

it('should create', async () => {
       await TestBed.runInInjectionContext(() => {
            const component = new AlertsComponent();
            expect(component).toBeTruthy();
        });
    });

© www.soinside.com 2019 - 2024. All rights reserved.