【问题标题】:Angular 10 Unit test - Component instance is returning undefinedAngular 10 单元测试 - 组件实例返回未定义
【发布时间】:2020-11-25 22:29:43
【问题描述】:

我在组件实例上获得了未定义的值。在我从 angular 8 升级到 angular 10 之前它一直在工作。我在测试中唯一改变的是,async() 到 waitForAsync(),因为 async 已被弃用。

 describe('ProtocolInfoComponent', () => {
      let component: ProtocolInfoComponent;
      let fixture: ComponentFixture<ProtocolInfoComponent>;
    
      const mockActivatedRoute = new MockActivatedRoute({
        parent: new MockActivatedRoute({
          params: of({ studyId: 1001 })
        })
      });
    
      beforeEach(waitForAsync(() => {
        TestBed.configureTestingModule({
          imports: [FormsModule,
            AppConfigModule,
            SharedModule,
            HttpClientTestingModule
          ],
          declarations: [ ProtocolInfoComponent ],
          providers: [
            { provide: UserService, useClass: UserServiceStub },
          { provide: APP_CONFIG_STUB, useClass: APP_DI_CONFIG_STUB },
            { provide: StudySetupService, useClass: StudySetupServiceStub },
            { provide: StudyCreateService, useClass: StudyCreateServiceStub },
            { provide: ActivatedRoute, useValue: mockActivatedRoute },
            { provide: Router, useClass: RouterStub }]
          })
          .compileComponents().then(() => {
            AppInjector.setInjector(TestBed.inject(Injector));
          });
      }));
    
      beforeEach(() => {
        console.log('TestBed', TestBed.createComponent(ProtocolInfoComponent));
        fixture = TestBed.createComponent(ProtocolInfoComponent);
        console.log('Fixture',fixture);
        component = fixture.componentInstance;
        console.log('Component',component);
        fixture.detectChanges();
      });
    
      it('should create', () => {
        console.log('=====component=====',component)
        expect(component).toBeTruthy();
      });
    
      it('should have the study', () => {
        expect(component.study).not.toBe(null);
      });
    
      it('should have the responsibiltiies', () => {
        expect(component.responsibilities).not.toBe(null);
        expect(component.orgResponsibilities).not.toBe(null);
      });
});

我在测试中有控制台语句,以查看夹具和组件的值。两者都是未定义的。 它适用于其他测试,我有同样的 关于如何解决此问题的任何想法。

【问题讨论】:

    标签: angular angular10 angular-test


    【解决方案1】:

    终于搞明白了。在 providers 数组中,provide 之一是 useValue 而不是 useClass;

    { provide: APP_CONFIG_STUB, useValue: APP_DI_CONFIG_STUB }
    

    【讨论】:

      猜你喜欢
      • 2019-03-26
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-17
      • 2012-10-13
      • 2020-07-29
      相关资源
      最近更新 更多