问题
I have a parent component ValidateSessionComponentwhich has a child component LoginFormComponent. In my unit test, I want to emit a value from LoginFormComponent but I am unable to figure out how I can do so.
The HTML of the ValidateSessionComponent has reference of the LoginFormComponent.
<app-login-form #loginForm (formOutputEvent)="handleFormValues($event)" [userId]="username"></app-login-form>
The LoginFormComponent looks like
export class LoginFormComponent implements OnInit {
loginForm:FormGroup;
formData:LoginFormValues;
@Input() userId;
@Output() formOutputEvent: EventEmitter<LoginFormValues>;
existingUser:UserSigninInfo;
..
}
In the test, i want to emit formOutputEvent by calling formOutputEvent.emit(formData); But I can't figure out how to access formOutputEvent of LoginFormComponent in ValidateSessionComponent's spec.
fit('should send signin request on receiving form values ',(done)=>{
//let loginComponent:LoginFormComponent = TestBed.get(LoginFormComponent); //IF I UNCOMMENT THIS THEN I GET ERROR NO PROVIDER OF LOGINFORMCOMPONENT
let userService:UserManagementService = TestBed.get(UserManagementService);
component.loginForm.formOutputEvent.emit(new LoginFormValues('test@test.com','somepassword'));
spyOn(userService,'signinUser');
setTimeout(()=>{
expect(userService.signinUser).toHaveBeenCalledWith(new UserSigninInfo('test@test.com','somepassword'));
done();
},1000);
});
I thought I could use the ViewChild directive @ViewChild(loginForm) loginFormRef; but I suppose I'll get an ElementRef. I can't figure out how to access the formOutputEvent.
来源:https://stackoverflow.com/questions/58263959/how-can-i-get-reference-of-child-component-and-emit-a-value-from-child-component