简体   繁体   中英

How do I access elements of child component from parent for testing Angular 2?

I'm trying to get an element of child component from a parent component for testing in Karma-Jasmine. I have a component(parent) with contact form which in-turn has a username and password component(child) which is used for validating the form and displaying error messages. Now I need to test the alert messages of child component from the parent component. I tried following

   let parent = fixture.debugElement.query(By.css('input-component'));
   let child = parent.query(By.css('alert'));

But I did not manage to get any result. it just returns the parent HTML. I found a solution for E2E testing here but it doesn't work with Unit testing.

How can I accomplish the task. Here's the Plunker for explaining my scenario.

I found a solution for my problem. Seems that the properties 'dirty' and 'touched' does not get enabled while testing. So I manually enabled them after resetting or modifying form values by adding the following code...

component.parentForm.controls['childUser'].markAsDirty();
component.parentForm.controls['childUser'].markAsTouched();

I don't know if this is the right method to make it to work. But I could not find any other solution. Thank you. Hope this helps someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM