How can I ensure thorough test coverage without relying on Testbed?

We have implemented some custom form control components with decorators as follows:

@Component({
  selector: 'value-selector',
  templateUrl: './selector.component.html',
  styleUrls: ['./selector.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => ValueSelectorComponent),
      multi: true
    }
  ]
})

During the update of certain dependencies, particularly babel, we had to introduce the forwardRef. This caused our provider to change from:

useExisting: ValueSelectorComponent,
to:
useExisting: forwardRef(() => ValueSelectorComponent),

The JEST spec tests are set up to create a new instance using an instantiate method that is executed in the beforeEach block:

function instantiate({
  eventTypeService = {},
  translationService = {}
}): ValueSelectorComponent {
  return new ValueSelectorComponent(
    eventTypeService as EventTypeService,
    translationService as TranslateService
  );
}

describe(ValueSelectorComponent.name, () => {
  let component: ValueSelectorComponent;
  // abbreviated for clarity
  
  beforeEach(() => {
    mockTranslateGet = jest.fn().mockReturnValue(of());
    mockTranslationService = {
      get: mockTranslateGet
    } as unknown as TranslateService;

    getAllSpy = jest.fn();
    mockEventTypeService = {
      getAll: getAllSpy
    } as unknown as EventTypeService;
    
    // abbreviated for clarity
    component = instantiate({
      eventTypeService: mockEventTypeService,
      translationService: mockTranslationService
    });
  });

However, I am facing challenges in achieving code coverage for () and ValueSelectorComponent within the useExisting. Our test suite uses JEST, and all solutions discovered so far involve TestBed, which we do not utilize. Is there a way to ensure coverage for that particular line?

Answer №1

In Angular, providers are an essential part of the Dependency Injection system.

To utilize them effectively, you must make use of the DI system. This is where the TestBed becomes crucial:

  beforeAll(async () => {
    await TestBed.configureTestingModule({
      declarations: [ ValueSelectorComponent ]
    });
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance
  });

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

A guide to sending data via POST in Angular2 using a service class

As I venture into developing a simple application form and posting data to the server, my Angular2 skills are being put to the test. I am particularly curious about how to smoothly transfer the data from the component to the service and eventually onto th ...

Create the Angular 6 service within the directory "e2e/app"

After upgrading my Angular 4 to 6, I attempted the following command: ng generate service security/security However, the service was generated under the "e2e/app" folder instead of the expected "src/app" location. Below is an excerpt from my angular.json ...

How can I apply a class to an Angular tag that already has existing CSS classes in the HTML template?

I am looking to write code similar to the following: Note: I do not have control over the classes in the class property (style13, style121, style541), but I want to add another class from a variable in the TypeScript. For example: <div class="styl ...

What is the best approach for dynamically accessing or rendering Children within an Angular Component?

I am facing an issue with reusing a component called wrapper with different child components. I found some helpful resources such as this SO question and this article. However, these only address cases where the child component is known in advance. In my s ...

Typescript: The ConstructorParameters type does not support generics

Incorporating TypeScript 3.7, I created an interface featuring a property designed to accept a constructor function: interface IConstruct<T> { type: new (...args:ConstructorParameters<T>) => T; } I initially assumed that IConstruct<Us ...

What is the purpose of the .Class method in ng.core.component within ES5?

ng.core.Component({ selector:'myapp', template:'<h1>Hello World</h1>' }). Class( { constructor:function() } ); ...

Navigate to a new tab using this.router.navigate

Is there a way to redirect the user to a specific page with ${id} opening in a new tab, after clicking a button in an angular material dialog box? I want to leave the dialog box open while querying the new page. Currently, the redirect happens but not in a ...

Route Not Found: URL Segment 'homePage' does not match any existing routes

Every time I click the login button, I want to be redirected to the home page. However, I keep encountering this error message : Error: Cannot match any routes. URL Segment: 'homePage' This is my route configuration: { path: 'homePage&a ...

How can I display an ng-container or ng-template without using *ngIf?

I am trying to incorporate the tappable directive into the ion-card component within a custom component. I am using an @Input() myInputBool, similar to this: <ng-container *ngIf="myInputBool"> <ion-card> <ng-container r ...

Form a collection using multiple elements

I'm attempting to combine multiple arrays into a single array. For instance : array1= ['Joe','James','Carl','Angel','Jimmy',]; array2= ['22','11','29','43',&apo ...

Implementing routing for page navigation within an angular tree structure

Can someone assist me with integrating a route into an angular tree structure? Here is the HTML code snippet: <mat-tree [dataSource]="dataSource" class="tree-container" [treeControl]="treeControl"> <mat-tree-node class="btnLinks" *matTreeN ...

Having trouble with an Angular HTTP PUT request returning a 404 error for a valid URL on a JSON server!

After trying to implement Angular HTTP put using reactive forms for the first time, I encountered an issue. Whenever I use the code provided, I receive a 404 error. The error specifically points to a server URL that cannot be found (XHR PUT http://localhos ...

Executes the function in the child component only if the specified condition evaluates to true

When a specific variable is true, I need to call a function in a child component. If the variable is false, nothing should happen. allowDeleteItem = false; <ChildComponent .... removeItemFn={ deleteFn } /> I attempted to use the boolean variable wi ...

What steps can be taken to safeguard data while navigating within the Angular framework?

I am facing an issue with storing an array of items in a service (referred to as cart service) and displaying it in the component (cart.component.ts). The components bgview.component.ts and single.component.ts are involved in selecting individual items, wi ...

What are the steps to deactivate all formal controls?

I have developed a comprehensive form that resembles the one below: ... export function directoryForm( countries: CountryModel[], dealers: DealerModel[], translate: TranslateService ): FormlyFieldConfig[] { return [ { type: 'stepper ...

What is the source of Docker's node version information?

Within the Dockerfile, I specified the version node:14.17.6-alpine3.13. However, in the deployment log, it shows a different version, node:16.13.2-alpine. Can anyone shed light on why this discrepancy exists and how to rectify it? docker-compose deploy lo ...

Can TypeScript interfaces be used to achieve the same functionality as an abstract class?

I am currently working on developing a function that will return an array type with custom methods, allowing me to utilize it across various sections of the application. Typically, this is achieved using Abstract Classes where abstract methods are defined ...

Looking for giphy link within a v-for loop (Vue.js)

I am fetching a list of movie characters from my backend using axios and rendering them in Bootstrap cards. My objective is to search for the character's name on Giphy and use the obtained URL as the image source for each card. However, when I attemp ...

Loading only specific HTML list elements in segments

Within my Angular4 application, I am faced with a challenge involving a large list of li elements. The browser struggles to handle the thousands of li's being displayed when the user interacts with the ul element. This results in slow loading times an ...

Two primary router outlets featuring unique layouts

Design for all users Design for staff members (such as admin control panel) I am using a router-outlet with the first design. How can I switch to the second design at "/personnel"? I want to keep both designs intact since "personnel" has its own componen ...