Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Fixture DebugElement Query By class Not Returning Elements

As suggested by Angular.io Framework Testing documentation, I have been attempting to make use of DebugElement query using Angular Testbed + Karma test Runner. I have created a jqwidgets Tree component that produces li elements of class '.jqx-tree-item-li'. The following test using straight javascript on the DOM test passes GREEN:

    it('Elements of class jqx-tree-item-li found using getElementsByClassName ', (done) => {

    this.fixture.whenStable().then(
      () => {
        var elementArray = document.getElementsByClassName('jqx-tree-item-li');
        expect(elementArray.length).toBeGreaterThan(0); //passes without issue :)
        done();
      }
    );
  });

But this test in the SAME spec (identical Testbed setup) FAILS due to 0 elements returned:

   it('Elements of class jqx-tree-item-li found using Angular DebugElement ', (done) => {

    this.fixture.whenStable().then(
      () => {
        var elementArray = this.fixture.debugElement.queryAll(By.css('.jqx-tree-item-li'));
        expect(elementArray.length).toBeGreaterThan(0); //fails! why? :(
        done();
      }
    );
  });

Object Explorer Component Elements of class jqx-tree-item-li found using Angular DebugElement Expected 0 to be greater than 0.

Not the first time I have observed this and I have found that it will get root component elements, but I can't seem to get the DebugElement query to return elements within the component. Though the documentation states explicitly it will query the subtree. To date the work around has been just to javascript query like above which does function as intended.

Am I missing something here? Any suggestions on how to get DebugElement.query to work? If not, has anyone found issues with DebugElement query? Thank you.

like image 857
user7611503 Avatar asked Aug 05 '17 02:08

user7611503


1 Answers

You made couple of mistakes

  • detectChanges is missing
  • Querying through document which is wrong you should use fixture.debugElement

    it('Elements of class jqx-tree-item-li found using getElementsByClassName ', (done) => {
    
        this.fixture.whenStable().then(
            () => {
                fixture.detectChanges(); // missed
                var elementArray = fixture.debugElement.query(By.css('.jqx-tree-item-li')); // use fixture instance to 
                expect(elementArray.length).toBeGreaterThan(0); //passes without issue :)
                done();
            }
        );
    });
    
like image 170
Aravind Avatar answered Sep 22 '22 11:09

Aravind