Having difficulty accessing an element within ng-template during the unit test writing process with Jasmine

I am encountering an issue when trying to access a button inside an ng-container in my testing environment. Despite manually setting the value of the ngIf condition to true, the elements inside are not being rendered. Here is what I have attempted so far:

  • Adding async
  • Updating the value of the ngIf condition in beforeEach
  • Updating the value of the ngIf condition inside the it function itself

Unfortunately, none of these solutions seem to work as I continue to receive the error message "TypeError: Cannot read properties of null (reading 'nativeElement')"

it('should call assignGroup function', fakeAsync(() => {
  component.Show = true;
  fixture.detectChanges();
  let button = fixture.debugElement.query(By.css('#assignGrpBtn')).nativeElement;
  console.log(button); // getting null for the btn 
}));
<ng-container *ngIf="Show">
  <ng-template pTemplate="caption">
    <div style="float: left;">
      <button class="btn btn-secondary" (click)="assignGroup()" [ngClass]="{'assignGrpDisabled': assignToGrpBtnStatus,'assignToGrpBtn':!assignToGrpBtnStatus}" id="assignGrpBtn"><i class="fa fa-plus-square fa-lg"></i> Assign to Group(s)</button>
    </div>
  </ng-template>
</ng-container>

Answer №1

It seems that your TestBed is not familiar with rendering the pTemplate directive.

To resolve this issue (assuming you are using prime-ng), try the following approach:

import {TableModule} from 'primeng/table';

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        YourComponent,
        // If simply adding TableModule to imports does not solve the issue, consider including
        // the directive for pTemplate.
        // PTemplateDirective
      ],
      imports:[TableModule]
    }).compileComponents();
  }));

By importing TableModule and adding it to the imports array, the test case should be able to render it correctly.

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

How can you establish a TypeScript project that employs classes shared by both client and server applications?

I am working on a project that consists of two components: ServerApp (developed with nodejs using NTVS) and BrowserApp (an Html Typescript application). My goal is to share classes between both projects and have immediate intellisense support. Can you pr ...

Enable users to designate custom methods as either asynchronous or synchronous

These are my TypeScript method signatures: onPinnedError?(info: HavenInfo, req: Request, res: Response): HookReturnType; async onPinnedError?(info: HavenInfo, req: Request, res: Response): HookReturnType; onPinnedUnhandledRejection?(info: HavenInfo, ...

"Encountering issues with importing Splitpanes while using VueJs and TypeScript combination

My VueJS view was originally written in JavaScript using the component "splitpanes" from npm package. The code was functioning well with the following structure: <template> <div> <Splitpanes :dbl-click-splitter="false" :horizont ...

Tips for utilizing string interpolation in the style tag of an Angular component

@Component({ selector: 'app-style', template: ` <style> .test { color: {{ textColor }} } </style> ` }) export class StyleComponent { textColor = "red"; } The current method doesn't appear to b ...

Ways to resolve the issue with the Argument of type 'Date[]' not matching the parameter type '(prevState: undefined) in React

I've encountered an issue while trying to construct my project. The error message reads as follows: Argument of type 'Date[]' is not assignable to parameter of type '(prevState: undefined) Here's the excerpt of the code in questio ...

Steps for combining a sequence of subsequent subscriptions in RxJS

In my approach, I followed the code below. this.service1.info .subscribe(a => this.service2.getDetails(a.id) .subscribe(b => { this.doStuff(b); }) ); Lately, it has come to my attention that we will be adding more steps that gradu ...

Metamorphosed Version.execute SourceText and TypeScript Writer

I'm currently working on transforming a TypeScript source file and I have successfully made the necessary changes to the code. Despite seeing my transformed node in the statements property of the transformed source file, the SourceFile.text property d ...

Accessing the property of an object with TypeScript

I am working with an array of objects, where each object contains two properties: {key:count} When configuring my chart, I need to set the data source in this format: {meta: "unknown", value: [the count of unknown]}, {meta: "male", value: [the count of ...

Outdated compiler module in the latest version of Angular (v13)

After upgrading to Angular 13, I'm starting to notice deprecations in the usual compiler tools used for instantiating an NgModule. Below is my go-to code snippet for loading a module: container: ViewContainerRef const mod = this.compiler.compi ...

Issue with minifying AngularJS and TypeScript route configuration for safe minification

Currently, I have a package containing multiple js files that were created from typescript files. However, when I attempt to apply minification to the package, the webpage encounters errors. The error message displayed on the Chrome console is: Uncaug ...

Angular 16 SSR encounters a TypeError when the 'instanceof' operator is used on a value that is not an object

I have been facing an issue while updating my Angular application from version 15 to 16. Everything seems to work fine with Angular, including building for Angular Universal without any errors. However, when I attempt to serve using npm run serve:ssr, it t ...

How to Delete Multiple Rows from an Angular 4 Table

I have successfully figured out how to remove a single row from a table using splice method. Now, I am looking to extend this functionality to remove multiple rows at once. html <tr *ngFor="let member of members; let i = index;"> <td> ...

Pass a string with quotation marks to a component input in Angular 6

Need help with passing a string input to a component: @Component({ selector: 'abcComponent' template: ` <div> .... </div>` }) export class AbcComponent { @Input() text:string; } I am trying to send a strin ...

errors.ts:30 ERROR Error: Unhandled promise rejection: Error: No routes found for specified URL Segment: 'products,%20productId'

I'm in the process of learning Angular by following a tutorial on a website. You can find it here: https://angular.io/start/routing Everything is going smoothly so far, except for the section on routing. If I add 'products/1' to the end of ...

Do Angular pipe promises have the potential to disrupt an application's functionality?

Within my small library, I have implemented a translation pipe that functions perfectly when using Observables. The relevant code snippet can be found here: this.localizationChanges.subscribe(() => { this.fluentService .translationObservable ...

Error: Vue Prop is undefined and cannot be utilized within a v-for loop when using TypeScript and decorators

Hey there, I'm currently utilizing Vue along with typescript and facing an issue with props in v-for where it's not rendering anything. Check out the code snippet below for reference I've experimented with computed props, setting default va ...

Styling array of arrays

When retrieving data from an API, the structure looks like this: "key1" : { "subkey1" : value "subkey2" : value "subkey3" : value } "key2" : { &q ...

Receiving an error when triggering an onclick event for a checkbox in TypeScript

I am creating checkboxes within a table using TypeScript with the following code: generateTable(): void { var table = document.getElementById("table1") as HTMLTableElement; if (table.childElementCount == 2) { for (var x = 0; x < 2; x++) ...

Using ngFor to dynamically populate drop-down options from a key value object in Angular 2

How can I use ngFor in Angular 2 to dynamically populate options in dropdown menus from a key value object? Below is the JSON data: { "employment": { "0": "Employed", "2": "Un-employed", "3": "Retired", "4": "Self" "V ...

Embed a React component within an Angular 6 application

I am attempting to integrate a React component into an Angular 6 project. The React component I am using is from the tic-tac-toe tutorial which can be found at this link. Prior to adding the React component, my Angular host component was functioning corre ...