Trouble with querying NG elements using "queryAll(By.css)" in Angular and Jasmin unit testing

I've encountered an unusual problem that needs to be resolved for me to successfully complete a unit test for a project I'm currently engaged in.

Here is what my unit test currently looks like:

    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);    

  });

Accompanied by the corresponding HTML code:

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

The issue arises when I attempt to console.log links with an HTML element lacking an "ngIf" or "ngFor" statement, resulting in a "[DebugElement]." However, if I use an HTML element with an "ngIf" or "ngFor" statement, it simply returns a "[]." This poses a problem as I need to incorporate the following code snippet into my unit test:

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

Nevertheless, since queryAll(By.css) yields nothing when applied to an HTML component with an "ngFor," this condition becomes invalid. How can I overcome this obstacle?

And for those curious minds, rest assured that the mock data is present. jsonData.hamburgerMenu[0].menuItems comprises the data shown below:

https://i.sstatic.net/QeqRa.png

Answer №1

Here are some suggestions for troubleshooting:

  • Try running the test in a browser window and verify
    • Are the expected elements visible in the browser?
    • Can you locate the elements using your selector? (-> Go to the elements tab in the browser dev tools, press ctrl + f, and search for .NavMenuItem)
  • Check if your logic involves async code. If so, consider using an asynchronous testing approach.
    • Utilize fakeAsync in your test to determine if there are any remaining open timers. (The test will fail if there are.)
  • Verify the purpose of appMenuItem. Is it simply a variable name, or does it represent a directive or component?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to enable code sharing between two TypeScript projects housed within the same repository?

Our project has the following structure: api (dir) -- package.json -- tsconfig.json -- src (dir) -- client (dir) ---- package.json ---- tsconfig.json ---- src (dir) The "client" directory houses a create-react-app project that proxies to the API d ...

What is the best way to showcase a collection of inherited objects in Angular?

How can I efficiently display a list of various objects that inherit from the same abstract class in an Angular application? What is considered optimal practice for accomplishing this task? Consider the following basic model: abstract class Vehicle { ...

Struggling to dynamically create an identifier and data-bs-target, but experiencing difficulty in doing so

<ul> <li data-info="Amount in (₹)">{{depositeAmt}}</li> <li data-info="Status"> <button class="statusbtn Process" data-bs-toggle="collapse" data-bs-target="#colla ...

Combining the redux toolkit function createAsyncThunk with Angular's HttpClient by leveraging the ApiService

Currently, I am working on incorporating @reduxjs/toolkit into an Angular project. Is there a way to pass an Angular service as a parameter to the callback of createAsyncThunk instead of utilizing fetch directly? I referenced the documentation for an exa ...

Angular2's service executing http method is limited to just once

I have a service that is responsible for retrieving information from the server. The goal is to execute the request only once and then share the data with every component in the application. Currently, my code looks like this: @Injectable() export class P ...

Issue with hardhat failing to detect balance transfer from smart contract

I am currently in the process of creating tests for a smart contract that I have developed. Below is a simplified version of the smart contract: Please Note: I have hard-coded the value to ensure accuracy regarding the amount leaving the contract. functio ...

Encountered an unexpected interpolation ({{}}) in column 3 of Data Bind RouterLink (Angular 2) that was expecting an expression

Encountering difficulties passing data to my routerLink. The goal is to change the route when the id reaches 4 within the ngFor loop. <input type="button" class="btn-cards" [ngClass]="getStyle(negociacao)" [routerLink]="['/{{negociacao.rota}}&apo ...

Typescript: Ways to fix the error 'rxjs/Rx does not have any exported member 'SubscriptionLike'

I'm attempting to replicate the steps outlined in this tutorial found here https://www.youtube.com/watch?v=gxCu5TEmxXE. However, upon running tsc -p, I encounter an error. Is there a specific import that I am missing? ERROR: node_modules/@angular/co ...

Incorporating SVG graphics within a SharePoint web part

I am in the process of developing a webpart for SharePoint using the SharePoint Framework, TypeScript, and ReactJS. I have encountered an issue while trying to incorporate an svg image into my webpart code, resulting in build errors. Initially, I used the ...

Changing Image to Different File Type Using Angular

In my Angular Typescript project, I am currently working on modifying a method that uploads an image using the input element of type file. However, I no longer have an input element and instead have the image file stored in the assets folder of the project ...

What is the process for invoking a microservice (constructed in express js) from an angular application that is currently communicating with a sails js backend?

I had initially developed an application with Angular frontend and Sails JS backend. However, I recently separated some of the backend functions into a micro-service using Express. Now, I am looking for guidance on how to call these functions from my mai ...

Mocking store.dispatch in Jest with TypeScript did not result in any function calls being made

Testing Troubles I'm a beginner in the world of testing and I'm facing some challenges. Despite going through all the documentation on jest, I couldn't find information specific to TypeScript cases. Currently, I'm on a quest to figure ...

I need help figuring out how to incorporate dynamic checkboxes in Angular

Currently, I am working on integrating dynamic forms into my Angular application and I am referring to the https://angular.io/guide/dynamic-form guide for guidance. Specifically, I have a checkbox question that consists of more than four options to choose ...

An issue occurred when clicking on a line due to the filter

Issue at Hand: Currently, I am facing a problem where selecting an item from the list by clicking on the button leads me to access the information of a different item when the filter is applied. Desired Outcome: I wish to be able to access the correct inf ...

Converting an array of objects to an array based on an interface

I'm currently facing an issue with assigning an array of objects to an interface-based array. Here is the current implementation in my item.ts interface: export interface IItem { id: number, text: string, members: any } In the item.component.ts ...

New feature in Next.js 13: Utilizing a string within className

Looking for a way to dynamically generate radio buttons in Next.js using a list of strings? Utilizing Tailwind CSS classes, you can modify the appearance of these buttons when checked by leveraging the peer/identifier classname. But how do you include th ...

Unexpected behavior with the ion-datetime time picker on an Android device

I am encountering challenges with a Date and Time entry feature in my Angular/Ionic application that involves date pickers. When I tap on the Time field, the time picker opens. Everything works perfectly in my browser - I can select a time, spin the value ...

Using ngFor to loop through an array of objects and calculate the number of elements in an array property

Currently I am developing a web application using Angular 6. The data is obtained in the form of an array of objects from Firebase, and my intention is to present this information to the user by utilizing ngFor. export interface Competition { createdAt: ...

What is the best way to customize the tooltip in VS Code for TypeScript type aliases?

Here is an issue with the code snippet below: type char = 'a' | 'b' | 'c' | 'd' | 'e' | 'f'; const s: string = 'foo'; const [c]: char = s; // [ERROR]: Type 'string' is not assi ...

Using Angular to dynamically modify the names of class members

I am working with an Angular typescript file and I have a constant defined as follows: const baseMaps = { Map: "test 1", Satellite: "test 2" }; Now, I want to set the member names "Map" and "Satellite" dynam ...