angularjs - How to unit test if an angular 2 component contains another component -
i'm quite new angular 2.
i have component in turn has other components in template.
how write unit tests check if parent component consists of other components.
mentioning sample or directing me resource helpful.
mycomponent.ts:
import { component } '@angular/core'; @component({ selector: 'my-component', templateurl: `<div> <other-component></other-component> </div>` }) export class mycomponent{ } othercomponent.ts:
import { component } '@angular/core'; @component({ selector: 'other-component', templateurl: `<div> <h1>other component</h1> </div>` }) export class othercomponent{ }
to test if component, when compiled, contains other components:
- inject component you're testing
- inject child components
- create parent component
- detect changes
- use
queryselectororqueryselectorallfind child components
i typically check element exists , further testing in spec individual child component.
import { testbed, async } '@angular/core/testing'; import { appcomponent } './app.component'; import { othercomponent } './other/other.component'; describe('appcomponent', () => { beforeeach(async(() => { testbed.configuretestingmodule({ declarations: [ appcomponent, othercomponent ], }).compilecomponents(); })); it('should create app', async(() => { const fixture = testbed.createcomponent(appcomponent); const app = fixture.debugelement.componentinstance; expect(app).tobetruthy(); })); it('should have other component', async(() => { const fixture = testbed.createcomponent(appcomponent); fixture.detectchanges(); const compiled = fixture.debugelement.nativeelement; expect(compiled.queryselector('app-other')).not.tobe(null); })); }); checking null queryselector determine if component exists. queryselector mdn:
returns null if no matches found; otherwise, returns first matching element.
if you'd check there multiple instances of same child component, can use queryselectorall , check length property:
expect(compiled.queryselectorall('app-other').length).tobegreaterthan(4);
Comments
Post a Comment