简体   繁体   English

如何从父级访问子级组件的元素以测试Angular 2?

[英]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. 我正在尝试从父组件中获取子组件的元素,以在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. 我有一个带有联系表单的组件(父),该组件又具有一个用户名和密码component(child),用于验证表单和显示错误消息。 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. 它只是返回父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. 希望这对某人有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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