`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

Using React MUI to implement a custom Theme attribute within a component

I have a CircularProgress element that I want to center, and to make the styling reusable, I decided to create a theme.d.ts file: import { Theme, ThemeOptions } from '@mui/material/styles' declare module '@mui/material/styles' { inte ...

Setting up Angular Universal on an already existing Angular 2 application with the help of the CLI

Encountering obstacles while trying to integrate the universal CLI into an existing Angular 2 application by following the guidelines provided in this link: During the initial command to install angular-universal: npm install body-parser angular2-univers ...

Is there a way to merge the .load function and the document.referrer function together?

Is there a way to load a specific div from the previous page that a user originated from using a form? $(document).ready(function() { $("#div_to_be_populated").load('url #div'); }); How can I utilize the document.referrer function in the ur ...

JS Unable to get scrollIntoView function to work with mousewheel event

I have been working with the script provided above. It correctly displays the id in the browser console, but unfortunately, it is not triggering the scrolling function as expected. var divID = null; var up = null; var down = null; function div(x) { s ...

If you scroll quickly, watch out for the flickering of the fadeIn and fadeOut

I have a script that fades in an element once the user scrolls more than 145px from the top of the page. $(window).scroll(function(){ if ($(this).scrollTop() > 145) { $('#fademenu').fadeIn(); } else { $('#fademenu').fadeOut(); } } ...

Icon for TypeScript absent from npm package listings

Recently, I created a package and uploaded it to the npm repository. The package was displayed with an icon labeled "ts" on the website. https://i.stack.imgur.com/LoY1x.png The accompanying package.json showcased the inclusion of the "ts" icon - https:// ...

`The ng-binding directive seems to be malfunctioning while ng-model is functioning properly

Currently, I am in the process of learning how to utilize Angular (1.3.10). My objective is to create two input fields that will specify the suit and value for a hand of playing cards. In my attempts to achieve this, I have encountered an issue. When I man ...

Save multiple form values within a single cookie

As someone who is new to JavaScript, I am seeking some guidance. I came across a code snippet online that allows for saving form input values in separate cookies: function storeValues(form) { setCookie("field1", form.field1.value); setCookie( ...

Purge the external CSS files

Scenario In my React Router setup, most pages include their own .css files along with the default antd (UI framework) stylesheet: import '../styles.css'; This ensures that all components inherit these styles automatically. Issue at Hand Now, I ...

Stop/continue a stopwatch Observable

I'm trying to create a basic stopwatch using angular/rxjs6. I've managed to start the timer, but I'm struggling with pausing and resuming it. source: Observable<number>; subscribe: Subscription; start() { this.source = tim ...

Populate an array of objects with various key-value pairs

In my @change method, I receive the following values: changeAttr(id, key, value) { const selections = []; }, id can be any number, key could be: color, size, sex, etc..., and value could be: red, 8, female, etc. Initially, the values might look like ...

Having trouble sending a request in next.js with Docker during the build process?

When utilizing the getStaticProps function to send a request to my backend API from another Docker container, I am encountering an issue. Despite ensuring that the API URL is accurate, the static page fails to be created. This is due to the requirement for ...

Is the process.env variable used universally for environmental variables, or is it specifically designed for use in Node.js

Can process.env function as a universal environment variable or is it exclusive to NodeJs? https://nodejs.org/dist/latest-v8.x/docs/api/process.html#process_process_env Instructions on setting it using the node command are provided: $ node -e 'proc ...

Animating with React using the animationDelay style does not produce the desired effect

Is there a way to apply an animation to each letter in a word individually when hovering over the word? I want the animation to affect each letter with an increasing delay, rather than all at once. For example, if scaling each letter by 1.1 is the animatio ...

Implementing Security Measures for ExpressJS Static File Server

Recently, I set up an authentication system following a tutorial on express.js and passport.js. In the past, my express server setup used modRewrite as shown below: var express = require('express'); var modRewrite = require('connect-mod ...

Using TypeScript will result in errors when attempting to use the Promise object and the Awaited keyword

In this example, I am trying to ensure that the function foo does not accept a Promise as an argument, but any other type should be acceptable. export {} function foo<T>(arg: T extends Promise<unknown> ? never : T) { console.log(arg); } asy ...

Monitoring $scope modifications within a directive: A simple guide

I am currently working with a directive that looks like this: app.directive('selectedForm', function(MainService) { return { scope: { formName: '=currentForm' }, restrict: 'E', ...

Interact with multiple databases using the singleton design pattern in a Node.js environment

I need to establish a connection with different databases, specifically MongoDB, based on the configuration set in Redis. This involves reading the Redis database first and then connecting to MongoDB while ensuring that the connection is singleton. Here i ...

The inclusion of Angular 2 router queryParams in the URL is not happening

I implemented an auth guard to protect certain pages of my web-app. In order to enable users to return to the page they intended to access, I tried adding queryParams to the URL during a redirect. Initially, the code below worked as expected. However, rece ...

I'm curious about the process by which custom hooks retrieve data and the detailed pathway that custom hooks follow

//using Input HOOK I am curious to understand how this custom hook operates. import { useState } from "react"; export default initialValue => { const [value, setValue] = useState(initialValue); return { value, onChange: event =&g ...