Altering the properties of a specified element within TestBed using the overrideComponent method

We are implementing TestBed.overrideComponent() to substitute a component with custom behavior.

TestBed.overrideComponent(CoolComponent, {
    set: {
      template: '<div id="fake-component">i am the fake component</div>',
      selector: 'our-cool-component',
      inputs: [ 'model' ]
    }
  })

This manipulated component contains a ViewChild element that we configure in the ngOnInit lifecycle method:

@Component({
  selector: 'our-cool-component',
  templateUrl: 'cool.component.html'
})
export class CoolComponent implements OnInit, OnDestroy {
  @Input() model: SomeModel
  @ViewChild(CoolChildComponent) coolChildComponent;

  ngOnInit() {
    this.coolChildComponent.doStuff();
  }
}

The CoolComponent is encapsulated within a larger Wrapper component.

During fixture.detectChanges() on the Wrapper fixture, an issue arises when accessing the CoolComponent, as calling doStuff() fails due to CoolChildComponent being undefined.

We are exploring options to mock or stub the CoolChildComponent of the CoolComponent. Unfortunately, directly referencing it from the Wrapper is proving challenging since it is only accessible through the template, not as a direct property of the component.

Answer №1

When initializing the component: 
   
   ngOnInit() {
      this.coolChildComponent.doStuff();
   }

this can be changed to:

After the view is initialized:
   
ngAfterViewInit() {
  this.coolChildComponent.doStuff();
}

This change is recommended here:

The ViewChild variable is set before ngAfterViewInit callback, which ensures proper timing of child component initialization.

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

When attempting to compile Angular in production mode, errors may arise such as the Uncaught SyntaxError caused by an Unexpected token '<'

I encountered some errors in the console of my Angular 8 app. When I opened the browser window, it was blank and this error appeared: Uncaught SyntaxError: Unexpected token '<' I tried running different ng build commands such as: ng build --b ...

How to prevent right-clicking on an entire website using Angular, not just specific pages

I have been searching for a solution to disable right-click on my entire Angular 2+ application, but all I can find are solutions that only work for specific components such as, <someSelector appDisableRightClick></someSelector> Where "someSel ...

What is the best way to capture the current state of Angular's components?

Creating an estimate application using angular-cli, I have a unique concept where users can add a dynamic number of child components. It is essential to store the state and data of these components for future edits and exports. ...

Guide to adding information to a table with the help of an "interface" in Angular 6 and utilizing Typescript

Looking for some guidance with Angular as I am just starting out. I am currently trying to send an API request in angular 6 using Typescript. However, I am facing difficulties when it comes to adding data to a table. Check out my code on: Codepen In my p ...

Using a Component as a Property in Angular

There is a small gridComponent: @Component({ selector: 'moving-grid', templateUrl: './grid.component.html', styleUrls: ['./grid.component.css'] }) export class GridComponent { @Input('widgets') ext ...

Encountered a hiccup during the installation of ssh2-sftp-client on Next.js

I'm looking for a way to save uploaded files in my domain's storage using SFTP. I came across the multer-sftp package, but when I attempted to run the command yarn add multer-sftp ssh2-sftp-client, I encountered a strange error with the second pa ...

Convert parameterized lambdas for success and failure into an observable using RxJS

There is a function exported by a library that I am currently using: export function read( urlOrRequest: any, success?: (data: any, response: any) => void, error?: (error: Object) => void, handler?: Handler, httpClient?: Object, ...

Tips for receiving @ mentions in PrimeNg Editor using Quill and quill-mention with Angular

Currently, I have been given the task of adding a mentions feature to our text editors. The editor I am working with is the PrimeNg Editor, built on Quill. After some research, I came across the package quill-mention, which appears to be a potential soluti ...

Discover the Magic of Angular 8 and Bootstrap 4 Tooltips

I'm trying to implement tooltips from Bootstrap 4 into my web application. According to Bootstrap documentation, I should initialize the tooltips with the following code: $(function () { $('[data-toggle="tooltip"]').tooltip() }) (Implement ...

Explaining the distinction between include and rootDir in tsconfig.json

According to the information provided, include defines an array of filenames or patterns that are to be included in the program during the compilation process. On the other hand, rootDir specifies the path to the folder containing the source code of the ap ...

Alter the Color of the 'div' According to the Background

At the bottom right of my website, there is a black chatbot icon. The web footer also has a black background. To create a clear contrast, I have decided to change the color of the chatbot to white as users scroll to the bottom of the page. I implemented t ...

Tips for converting numerical values in a JSON object to strings within a TypeScript interface

{ "id": 13, "name": "horst", } in order to interface A { id: string; name: string; } When converting JSON data of type A to an object, I expected the conversion of id from number to string to happen automatically. However, it doesn' ...

Modifying the version target of TypeScript code results in the TypeScript Compiler being unable to locate the module

After installing signalr via npm in Visual Studio 2019, I encountered an issue. When the target in my compiler options is set to ES6, I receive the error TS2307 (TS) Cannot find module '@microsoft/signalr.'. However, when I change the target to E ...

What is the best way to first identify and listen for changes in a form

In Angular, there are reactive forms that allow you to track changes in both the complete form and specific fields: this.filterForm.valueChanges.subscribe(() => { }); this.filterForm.controls["name"].valueChanges.subscribe(selectedValue => { }); ...

Angular 2: The unsubscribe property is not defined

I have been working on creating an ObservableTimer that counts up to a specific number. The logic for this is already in place, but I am encountering an issue when attempting to unsubscribe from it. When I try to unsubscribe, I receive an error message say ...

The server's response is unpredictable, causing Json.Parse to fail intermittently

I have encountered a strange issue that is really frustrating. It all started when I noticed that my Json.Parse function failed intermittently. Here is the code snippet in question: const Info = JSON.parse(response); this.onInfoUpdate(Info.InfoConfig[0]); ...

Accessing information from req.files in a TypeScript environment

I am currently using multer for uploading images. How can I retrieve a specific file from req.files? Trying to access it by index or fieldname has been unsuccessful. Even when I log it, I see that it's a normal array, so I suspect the issue may be rel ...

What is the best way to invoke a method in a child component from its parent, before the child component has been rendered?

Within my application, I have a parent component and a child component responsible for adding and updating tiles using a pop-up component. The "Add" button is located in the parent component, while the update functionality is in the child component. When ...

When navigating to a new URL in Angular 7, the browser will automatically redirect to the home component

Currently, I'm developing a project using Angular 7.2.0. One issue I'm facing is that when I attempt to navigate to a particular page initially, such as: http://localhost:4200/comics?sort=series The browser always gets redirected to the root: ...

Angular 7 - Implementing periodic JSON data retrieval from server and maintaining local storage within Angular application

Seeking guidance on how to handle updating a static json file stored in the assets directory in an Angular 7 project. The goal is to periodically fetch a json from a server, check for updates, and perform post-processing on the data in the static file (ess ...