0

So I have this strange problem that I need fixed in order to complete a unit test for a project I'm working on.

My unit test currently looks like this:

    it('should display the navbar list', () => {

    component.courses = jsonData.hamburgerMenu[0].menuItems;

    fixture.detectChanges;
  
    const links = el.queryAll(By.css(".NavMenuItem"));
    
    expect(links).toBeTruthy("Could not find links");
    
    console.log(jsonData.hamburgerMenu[0].menuItems)
    
    console.log(links);    

  });

with the corresponding HTML looking like this:

<div *ngFor="let appMenuItem of courses; let i=index;" class="NavMenuItem">

The problem is, when I console.log links with an HTML element WITHOUT an "ngIf" or "ngFor" statement, it returns a "[DebugElement]." If I console.log an HTML element WITH an "ngIf" or "ngFor" statement, it gives me a "[ ]." This is problematic because I need to include the following code for my unit test to work:

expect(links.length).toBe(12, "Unexpected number of links");   

but, if my queryAll(By.css is returning nothing when used on an HTML component with an "ngFor," then that condition will not work. How do I solve this issue?

For those of you who are wondering, yes, the mock data is there. jsonData.hamburgerMenu[0].menuItems contains the following data:

enter image description here

Laurel Link
  • 195
  • 1
  • 4
  • 15

1 Answers1

0

Some ideas for debugging:

  • Run the test in a browser window and check
    • Are the elements you expect shown in the browser?
    • Do you find the elements with your selector? (-> Open the elements tab in the browser dev tools, press ctrl + f and enter .NavMenuItem)
  • Does your logic include async code? (In that case, you might need an async way of testing)
    • Use fakeAsync in your test to check if there a still open timers. (The test will fail in that case.)
  • What is appMenuItem? Is it just a variable name? It sounds like a directive or component.
slim
  • 414
  • 1
  • 7