【问题标题】:How can I get instance of a non-under test component inside my test case如何在我的测试用例中获取非测试组件的实例
【发布时间】:2020-02-03 23:09:19
【问题描述】:

我有一个组件,“ValidateSessionComponentwhich uses another component 'LoginFormComponent'. 'LoginFormComponent' emits a value whichValidateSessionComponentshould get should then callsigninmeethod of theUserManagementService”。我编写了以下测试用例,但出现错误“错误:StaticInjectorError [LoginFormComponent]: NullInjectorError: 没有 LoginFormComponent 的提供者!'

为什么会出现此错误,我该如何解决。

describe('ValidateSessionComponent tests with route parameters', () => {
  let component: ValidateSessionComponent;
  let fixture: ComponentFixture<ValidateSessionComponent>;

  beforeEach(async()=>{
    TestBed.configureTestingModule({
      declarations: [ LoginFormComponent, //I AM INJECTING THE LOGINFORMCOMPONENT HERE
        NavComponentComponent,
        ContentComponentComponent,
        FooterComponentComponent,
        HomepageContentComponentComponent,
        ShowErrorsComponent,
        ProgressBarComponent,
        SignupComponentComponent,
        HomepageContentComponentComponent,
        NewPracticeQuestionComponent,
        PraticeQuestionListComponent,
        QuestionDetailsComponent,
        PageNotFoundComponent,
        DialogBoxComponent,
        ValidateSessionComponent],
      imports:[ReactiveFormsModule,
        RouterModule,
        HttpClientModule,
        AppRoutingModule
      ],
      providers:[
        {provide: UserManagementService, useClass: MockUserManagementService},//mock user management service
        HelperService,
        DialogBoxService,
        {provide: APP_BASE_HREF, useValue: '/'}
      ]
    })
      .compileComponents();
  });


  beforeEach(() => {
    fixture = TestBed.createComponent(ValidateSessionComponent);
    component = fixture.componentInstance;
    //using component['activatedRoute'] instead of component.route to remove editor's error that route is private.
    /*
    this is the way to return different values from a spy based on the received argument. The route will have
    params like
    {
      username:..
      redirect-to:...
      additional-redirect-info:..
    }
     */
    spyOn(component['activatedRoute'].snapshot.paramMap,'get').and.callFake(function() {
     let param = arguments[0];
     console.log('param in fake function ',param);
     if(param==='username'){
       return 'test@test.com'
     }
      if(param==='redirect-to'){
        return '/home'
      }
      if(param==='additional-redirect-info'){
        return {somearg:'somevalue'}
      }
      console.log('returning unknown param',param);
     return param;
    });
    fixture.detectChanges();
  });

  fit('should send signin request on receiving form values ',(done)=>{
    let loginComponent:LoginFormComponent = TestBed.get(LoginFormComponent);
    let userService:UserManagementService = TestBed.get(UserManagementService);
    loginComponent.formOutputEvent.emit(new LoginFormValues('test@test.com','somepassword'));
    spyOn(userService,'signinUser');
    setTimeout(()=>{
      expect(userService.signinUser).toHaveBeenCalledWith(new UserSigninInfo('test@test.com','somepassword'));
      done();
    },1000);

  });
});

spec 中,如果我删除LoginFormComponent(其选择器为app-login-form),则会收到错误消息“无法绑定到'userId',因为它不是'app-login- 的已知属性-表格”。

【问题讨论】:

  • 你尝试在那里导入RouterTestingModule 吗?
  • 还有定义LoginFormComponent的模块?
  • 试过但没有奏效。

标签: angular6 angular-test


【解决方案1】:

为了获得组件的参考,我使用了 Viewchild。来自 ViewChild 的引用 - How can I get reference of child component and emit a value from child component

关于我面临的问题,似乎问题是多次包含LoginFormComponentValidateSessionComponent 的 HTML 引用了 LoginFormComponent

&lt;app-login-form (formOutputEvent)="handleFormValues($event)" [userId]="username"&gt;&lt;/app-login-form&gt;

到目前为止,这工作正常。然后我决定在ValidateSessionComponent中也包括LoginFormComponent通过DI的传递引用

constructor(private loginForm2:LoginFormComponent,private helper:HelperService,private dialogService:DialogBoxService,private activatedRoute:ActivatedRoute, private router:Router, private userManagementService:UserManagementService) { }

这开始导致错误StaticInjectorError(DynamicTestModule)[ValidateSessionComponent -> LoginFormComponent]: StaticInjectorError(Platform: core)[ValidateSessionComponent -> LoginFormComponent]: NullInjectorError: No provider for LoginFormComponent!

说实话,我无法弄清楚原因,即 Angular 内部发生了什么导致了这个问题

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 1970-01-01
  • 2018-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-11
相关资源
最近更新 更多