`Is there a way to effectively test an @Input component in Angular?`

Despite multiple successful attempts in the past, I am facing some difficulty getting this to function properly. Within my component, I have an input @Input data: Data, which is used in my template to conditionally display certain content. Oddly enough, during testing, the component does not seem to recognize that the data is present even when explicitly set with component.data = {props: values}. However, when running the tests individually using fit, they pass without any issues.

data.component.spec.ts

  beforeEach(() => {
    fixture = testbed.createComponent(DataComponent);
    component = fixture.componentInstance;
    component.data = {values: ['a', 'b', 'c']};
    fixture.detectChanges();
    component.ngOnInit();
    fixture.detectChanges();
  });

  describe('when viewing', () => {
    it('should load and display data', () => {
      const el = fixture.debugElement.query(By.css('[data-content]'));
      expect(el).toBeTruthy();
    });
  }

data.component.ts

export class DataComponent implements OnInit {
  @Input() data!: Data;

  constructor() {};
  
  ngOnInit() {
    console.log('init');
  }
}

data.component.html

<div *ngIf="data.values.length">
  <p data-content *ngFor="let value of data.values">{{value}}</p>
</div>

The error message I'm encountering:

Expected null to not be null "[data-content]"

Answer №1

It appears that the issue may be arising from the repeated use of both fixture.detectChanges and ngOnInit. The initial call to fixture.detectChanges automatically triggers the execution of ngOnInit.

To address this, consider the following revision:

  beforeEach(() => {
    fixture = testbed.createComponent(DataComponent);
    component = fixture.componentInstance;
    component.data = {values: ['a', 'b', 'c']};
    fixture.detectChanges(); // Only this line is needed to trigger ngOnInit
    // component.ngOnInit(); // You can remove this line as the first fixture.detectChanges() already handles it.
  });

  describe('when viewing', () => {
    it('should load and display data', () => {
      const el = fixture.debugElement.query(By.css('[data-content]'));
      expect(el).toBeTruthy();
    });
  }

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

Change the destination of an iFrame upon user click

Is it possible to redirect an iFrame to a different HTML page when clicked by the user? I have an iFrame that is essentially an HTML page. When I click on the iFrame, I want it to take me to another HTML page. This is my code: h1 { ...

What is the best way to programmatically set attributes on an HTML element or include HEAD/(LINK|TITLE) elements in Angular?

As I work on my Angular 12 application, I am facing the challenge of making it compatible with both LTR and RTL languages such as English and Arabic. This compatibility needs to be user-selectable within the application. Bootstrap, which provides the UI st ...

Modify the URL and show the keyword utilized in a search module

Does anyone know how to update the URL in a search bar? I'm using Redux to display search results, but the URL remains the same. How can I make the URL show the keyword being searched, like this: http://localhost/seach?q=keyword ...

Angular 2 Encounter Error When Trying to Access Undefined Property in a Function

Element: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-ore-table', templateUrl: './ore-table.component.html', styleUrls: [&a ...

the cached token retrieved by adal is consistently empty

To retrieve a cached token, I am utilizing the react-adal api import { authContext, } from '../auth' const AvatarContainer = () => { getPersonPhoto(authContext) return ( <Avatar /> ) } async function getPersonPhoto(au ...

Tips for updating the minimum value to the current page when the button is pressed on the input range

When I press the next button on the current page, I want to update the value in a certain way. https://i.stack.imgur.com/XEiMa.jpg I have written the following code but it is not working as expected: el.delegate(".nextbtn", "click", f ...

What is the process for resetting a JQueryUI effect animation?

I'm facing an issue with two timer bars that each wind down over a 5-second period. When I try to stop and reset the first timer, it simply continues from where it left off instead of resetting. The desired behavior is as follows: Timer1 starts User ...

The Discord.js guildMemberUpdate event: Everything you need to know

I am currently working on creating a welcome message bot using Discord.js. The goal is to have the bot send a welcome message through a webhook in a specific channel when a member gains access to it. Here's what I have so far: client.on("guildMe ...

Optimal techniques for Angular 2 and beyond

When creating a CRUD for an entity using a REST API, what is the recommended best practice for updating data? On the main screen where there is a list of elements and a new element is added through a modal, should the list be updated locally or by callin ...

How can I substitute a <tr> with my custom component in Angular2+ without disrupting the DOM layout or CSS styling?

Imagine you have a table snippet featuring rows of individuals and their test results: <tr> <td>John Doe</td> <td>18</td> </tr> <tr> <td>Jane Dober</td> <td>28</td> </tr> < ...

Encountering an error with "unexpected token import" while utilizing localize-router in an Angular 4

I am currently working on building an Angular 4 app with server-side rendering and language-specific route paths. I am using Angular CLI version 1.5.0-rc1 for this project. While everything seems to be functioning fine, I am facing a problem with incorpor ...

When resizing the window in IE8, the function DIV offsetWidth/Width/innerWidth returns a value of zero

My page is filled with many elements, one of which is the following DIV: <div id="root"> .................. <div id="child1"> ............. </div> <div id="child2"> ............... </div> & ...

Would it be better to lock a variable stored in req.session, or opt for a massive global variable instead?

As I delve into creating a game using node.js, the premise is sending units on missions and waiting for their return. The challenge lies in ensuring that the same unit cannot be sent on two different missions simultaneously, nor can two sets of units be di ...

The TS2339 error has occurred because the "email" property cannot be found on the specified "Object" type

I encountered an issue while using Angular 5, here is the code snippet : signIn(provider) { this._auth.login(provider).subscribe( (data) => { console.log(data); this.hideForm = false; this.emaill = data.email; ...

Is there a way to search for text and highlight it within an HTML string using Ionic

Welcome everyone! I am currently utilizing Ionic to load an article from a local HTML string. <ion-content padding> <p [innerHTML]="url"></p> </ion-content> The 'url' variable contains the local HTML string. My goal ...

Issue with onclick event not being triggered by Javascript function inside constructor

My current challenge involves implementing a function called makeHighlight within the SmartButton constructor. The purpose of this function is to execute whenever I click on the SmartButton object, which is represented by an image element. To achieve thi ...

In what way does ReactJS enable me to utilize constant functions before they are declared?

I'm intrigued by the concept of using a value before defining it in ReactJS. Let's explore this through an example: function CounterApp() { const [counter, setCounter] = useState(0); const increaseValueTwice = () => { increaseValue() ...

Submitting a form into a database with the help of AJAX within a looping structure

Trying to input values into the database using AJAX. The rows are generated in a loop from the database, with each row containing a button column. Clicking on the button submits the values to the database successfully. The issue is that it only inserts va ...

Using Angular2 to Toggle Checkbox Field Enabled and Disabled

As I dynamically render checkbox and combobox fields, the following functionality is performed: If the checkbox field appears as selected based on the API response, then the combo box appears as enabled; otherwise, it would be disabled. If a user selects ...

What sets Fetch apart from ajax and XMLHttpRequest that makes it impressively faster?

Over the past few days, I have been working on optimizing a client table for a project. The table contains over 10k clients, and as a result, it was taking a long time to load. The front-end team had implemented pagination, filters, and reordering, which ...