What is the process for running unit tests to check if data is available onInit using the ActivatedRoute?

Recently started unit testing in Angular with Jest and facing a challenge in testing whether the route is returning data or not. Is it possible to conduct unit testing to validate if data is being returned from the route in Angular? Any guidance would be greatly appreciated.

In my class component.ts

public data$: Observable<Data>;
  public salariesPerHours: salariesPerHoursViewModel[];

  private destroy$ = new Subject<boolean>();

  constructor(private activatedRoute: ActivatedRoute) {}

  public ngOnInit(): void {

    this.data$ = this.activatedRoute.data;
    this.data$?.pipe(takeUntil(this.destroy$)).subscribe((data: Data) => {
      this.salariesPerHours= data?.Salary?.salaryPerHour;
    });
  }

In test class compontent

import { ActivatedRoute, Data } from '@angular/router';
import { salariesPerHoursViewModel, SalaryType } from 'lib/store/store.barrel';
import { Subject } from 'rxjs';

import { SalaryComponent } from './salary.component';

const dataMock: salariesPerHoursViewModel[] = [
  {
      year:2018,
      salaryModifications:[
         {
            date:'2018-02-01T00:00:00',
            type: 'Salary',
            action:[
               {
                  logical :'0212834',
                  label:''
               }
            ]
         },
        ]
  }
]


describe('SalaryComponent', () => {
  let component: SalaryComponent;
  let activatedRoute: ActivatedRoute;

  beforeEach(() => {
    activatedRoute = new ActivatedRoute();
    component = new SalaryComponent(activatedRoute);
  });

  describe('ngOnInit', () => {
    beforeEach(() => {
      jest.spyOn(component, 'ngOnInit');
    });
   //need help here on how to verify if data is returned
   
  });

  describe('ngOnDestroy', () => {
    test('should complete the destroy observable', () => {
      component['destroy$'].next = jest.fn();
      component['destroy$'].complete = jest.fn();

      component.ngOnDestroy();

      expect(component['destroy$'].next).toHaveBeenCalledWith(true);
      expect(component['destroy$'].complete).toHaveBeenCalled();
    });
  });
});

Answer №1

When working with the activatedRoute in the ngOnInit method, it is crucial to focus on direct testing rather than spying.

What you need for input and output is this.activatedRoute.data as the input and this.salariesPerHours as the output.

Prior to calling ngOnInit, make sure to set your input like so:

this.activatedRoute.data = of(<mock containing Salary.salaryPerHour>);

After invoking ngOnInit, verify that this.salariesPerHours matches the expected value:

expect(this.salariesPerHours).toBe(<Salary.salaryPerHour from mock>);

Note that assigning this.activatedRoute.data with a sync-observable ('of' operator) allows for immediate callback invocation (assignment of this.salariesPerHours), ensuring the test can be controlled.

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

I encountered an error message stating "ConfirmationDialogComponent: No component factory found" while attempting to navigate through the

After successfully implementing the canDeactivate guard on the add and edit components, an issue arose when attempting to navigate from TypeScript code rather than using routerLink. The error message received was: "Error: No component factory found for C ...

Cucumber Wrangler

I am completely new to using protractor/cucumber and restler in Typescript. The code below is what I have so far for hitting an endpoint URL and getting the response: Given('Hit the {string}', async (string) => { browser.quit() var data: ...

Register the canDeactivate guard dynamically and trigger a confirmation prompt for navigation

Is it possible for a component to autonomously set up the canDeactivate guard in order to prompt or prevent user navigation with confirmation options like Yes/No? I am exploring this possibility due to the large scale of the application and how workflow c ...

Tips for elegantly merging two Observables within an RXJS pipeline

I am working on developing a log viewer using Angular. Upon user entry, I aim to load historical logs and also begin monitoring for new logs. Users have the ability to filter logs using a simple form that emits a query object. Each time the query changes, ...

Utilizing the useContext hook within a strictly Typescript-based class component

I have developed a pure Typescript class that serves as a utility class for performing a specific task. Within this class, I have created a context that is intended to be used universally. My goal is to utilize this context and its values within the pure T ...

Deploying my app on Heroku with two separate folders: a step-by-step guide

I am currently working on a project that involves two separate folders - one for the frontend and another for the back-end. My goal is to deploy both of these folders onto a single Heroku app. Within the server.js file, I have the following code snippet: ...

Guide to maintaining the route view in Angular

Is it possible to maintain the state of a page in Angular so that users can return to the same view when revisiting the same route? For example, let's say RouteA has a search bar where users can input a query. When a user enters a search term and vie ...

unable to generate a datatable using Angular and a local JSON file

I am diving into the world of Angular and trying to integrate the datatables library, which I have previously used with other languages, into my new project. I've been referencing the documentation provided here: . However, I'm encountering issue ...

Converting a string to an HTML object in Angular using Typescript and assigning it to a variable

I am facing an issue with passing HTML content from a service to a div element. I have a function that fetches HTML content as a string from a file and converts it into an HTML object, which I can see working in the console. However, when trying to assign ...

Node Express supplying outdated version of Angular app

I have encountered a problem with my Angular build. Locally, when I run Express it serves the new build perfectly fine. However, on the server, it is showing an old version of the build. I made sure to replace the old build with the new one and also made s ...

Is it possible to implement a cast operator in Typescript?

After using JSWEET to transpile a large Java project, I noticed that it changed types such as Enumeration<Object> directly to Enumeration<any> in TypeScript. Previously in the Java environment, it was possible to assign an array Object[] to an ...

Unable to run Angular due to an error: Cache cannot be moved as access is denied

Click here for the image I've come across this error before and have attempted the suggested solutions with no success. Here are the specifics: NodeJs version 18.7.0 has been installed. Angular, at its latest version (17), was globally installed with ...

Tips for organizing Python 3 unittests into different files and creating a script to selectively run them

I am looking to organize my Python 3.4 unit tests into separate modules while still being able to control which tests are run or skipped from the command line, as if they were all in the same file. However, I am facing difficulties in achieving this. Acco ...

Access a document and analyze its information

I am currently working with a file upload control that stores the selected file within it, as shown in the code snippet below: <div class="Block"> <label id="lbl">File </label> <input #fileInput type='file'/> </div ...

How can a new component be added as a child of an element without replacing or interfering with other

Whenever I dynamically generate components and attach them as children to an element upon creation, everything within that element gets deleted. Here's an example: public fn(event) { // Create component factory const factory = this.componentF ...

Is it feasible to make references to interfaces from an extended interface in Typescript?

I had the idea of enhancing all interfaces in HTMLElementTagNameMap with chained functionality. Since there are numerous interfaces, and all elements either are HTMLElement or extend it, I wanted a way to achieve something like this: interface HTMLElement ...

How to Insert a New User into the Database Using Angularfire2

During the login process, I implemented the following method: login() { this.auth.login(); this.authService.login().subscribe(() => { if (this.authService.isLoggedIn) { console.log("ADDING THE USER.."); // Insert a new user into the use ...

Tips for incorporating the ternary operator in JSX of a React component while utilizing TypeScript?

I am looking to implement a conditional rendering logic in React and TypeScript, where I need to return null if a specific condition is met, otherwise render a component using a ternary operator. Here is the code snippet I currently have: {condition1 && ...

Having trouble with Jest and React IntersectionObserver mock not functioning properly?

While working on my component.test.js file, I attempted to mock the IntersectionObserver using the following code: const mock = ()=>({ observe: jest.fn(), disconnect: jest.fn() }); window.IntersectionObserver = jest.fn().mockImplementation(mock) ...

Troubleshooting: Unable to Sort Column in ngx-DataTable Angular 4

As a newcomer to Angular, I have been encountering some challenges while using ngx-DataTable. I am currently utilizing a simple ngx-DataTable for basic operations. The issue I am facing is that the sorting functionality is not working on a specific column, ...