Error Message: Angular Unit Test Fails with "Cannot read property 'subscribe' of undefined"In this article, we will

My Angular app's unit tests using Jest are giving me the error "TypeError: Cannot read property 'subscribe' of undefined". Despite searching online, none of the solutions provided seem to work for me. Below is some relevant code:

page-view.component.ts


@Input() gotPlot!: Observable<void>;
...
ngOnInit() {
  this.initialiseColumnDefs();
  this.gotPlot.subscribe((response) => { //The error occurs on this line
    this.gotPlotValues(response);
  });
}

page.component.ts

@Component({
selector: 'page',
template: `
  <page-view
    [gotPlot]="gotPlotSubject.asObservable()"
  >
  </page-view>
`,
})

export class PageComponent implements OnInit {
...
public gotPlotSubject: Subject<void> = new Subject<void>();
...

async get_plot(arr: any): Promise<any[]> {

//This function calls a service and gets 'plotValues'
(await this.service.get_plot(input)).subscribe((data: any) => {

//plotValues is set to values gotten from the service here     

this.gotPlotSubject.next(plotValues);
});
}
}

page-view.component.spec.ts

@Component({
selector: 'page',
template: `
  <page-view *ngIf="gotPlotSubject.asObservable()" [gotPlot]="gotPlotSubject.asObservable()">
  </page-view>
`,
})
class PageMock {
public gotPlotSubject: Subject<void> = new Subject<void>();
constructor() {}
ngOnInit() {
let plotValues: any = [];
plotValues[0] = 1;
plotValues[1] = [1, 2, 3];
plotValues[2] = [2, 3, 4];
this.gotPlotSubject.next(plotValues);
}
}

describe('ViewComponent', () => {
let spectator: Spectator<ViewComponent>;

const createComponent = createComponentFactory({
component: ViewComponent,
declarations: [
  ViewComponent,
  PageMock,
],
imports: [TranslateModule.forRoot(), MaterialModule, AgGridModule, FormsModule],
providers: [HttpClient, HttpHandler, NGXLogger, NGXMapperService, HttpBackend, NGXLoggerHttpService, LoggerConfig],
schemas: [NO_ERRORS_SCHEMA],
});

beforeEach(() => {
spectator = createComponent();
});

it('should create', () => {
expect(spectator.component).toBeTruthy();
});
});

Could there be an issue with my PageMock setup? How can I properly mock the observable/subscribe functionality? Is there a more straightforward approach to handling this without relying so heavily on observables and subscribe? It seems like these features are complicating the Unit Testing process unnecessarily.

Answer №1

One possible solution is:

@Component({
  selector: 'page',
  template: `
    <page-view *ngIf="gotPlotSubject.asObservable() | async" [gotPlot]="gotPlotSubject.asObservable()">
    </page-view>
  `,
})

Take note of the async pipe used with *ngIf. The observable value on an *ngIf will always be true. You may even consider removing the asObservable() calls, as they might not be necessary, but it's worth experimenting with different approaches.

Dealing with RxJS in testing scenarios can definitely pose a challenge.

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

Ionic 3 Local Notification spamming a particular page with excessive pushes

Recently starting out with Ionic, I encountered an issue while developing a basic app that should display a specific page by opening a Local Notification. The problem arises when I create multiple notifications – after clicking on the second notification ...

What is the method for placing a title in the initial column with the help of v-simple-table from Vuetify.js?

I am interested in using the v-simple-table UI component from Vuetify.js to create a table similar to the one shown below. After creating the code in codesandbox and previewing the output, I noticed that the title is not aligned properly. HTML↓ < ...

Issues with Await and Async functionality in Angular and Ionic 4 causing unexpected behavior

Struggling to show error messages during the sign-up process? Constantly encountering the same issue in your code? The error TS1308 is throwing you off: 'await' expression is only allowed within an async function. Take a look at this problemati ...

Angular button will be disabled if the form control is empty

Is there a way to deactivate the search button when the text box is empty? I attempted to use the "disabled" attribute on the search button, but it didn't work. Here is my HTML code: <div class="col-md-5 pl-0"> <div class="in ...

react-i18next: issues with translating strings

I encountered a frustrating issue with the react-i18next library. Despite my efforts, I was unable to successfully translate the strings in my application. The relevant code looked like this: App.tsx: import i18n from 'i18next'; import { initR ...

Error TS2322: The specified type Login cannot be assigned to the given type

I've been facing an issue while working on my app in react native. The error message I keep encountering is as follows: TS2322: Type 'typeof Login' is not assignable to type ScreenComponentType<ParamListBase, "Login"> | undefined Type ...

Mastering the implementation of opaque tokens in Angular 2

Hey there! I'm having trouble with opaquetoken, is there something I missed? Check out my Plunk example here. Here's the relevant code snippet from app.ts: export const SbToken = new OpaqueToken('myToken'); const testfile = 'Hel ...

Protractor: Stuck on the current piece of Code

Why is the "else" code inside the "IsPresent()" function not getting executed in Protractor with Jasmine framework? The "IF" code works fine, but when I provide a value from an Excel file, the execution stops at the "IF" block. Any suggestions on why it&ap ...

Sorting in the TypeScript/Angular table is functioning properly on every column except for the initial one

Even after carefully following the information provided in the official documentation and implementing the example as suggested, I'm still struggling to sort my first column in descending order. Whenever I attempt to sort by another column and then cl ...

Configuring .NET Core to send authentication cookies to a separate domain

I am facing an issue with using cookies on the frontend, which has a domain different from the backend. The backend is built with .Net Core and the frontend with Angular. I have learned that I need to set withCredentials: true when making http calls. Howev ...

Exploring Angular 10: Managing Two Promises in ngOnInit

I am currently working on integrating the Strava API into my Angular app. To summarize briefly: When a user clicks on a button to connect to Strava They are redirected to Strava for authentication (using PKCE) Strava then redirects back to my app with a ...

Testing components in Angular using Renderer2

Recently, I came across an Angular component with the following structure: constructor( @Inject(INJECTION_TOKEN_WINDOW) private window: Window, private renderer: Renderer2 ){} ngOnInit() { this.renderer.addClass(this.window.document.body ...

Unable to initialize default values on Form Load in Angular Reactive Forms

My goal is to make an HTTP request by passing an ID, then take the response and assign the values to form fields. I attempted using setValue and patchValue methods, but they did not yield the desired results. spService itemData = new ItemData() getIte ...

Evaluate the functionality of a designated button using its unique identifier

Within my HTML file, there is a button that has the following structure: <a class="sub-menu-button" [matMenuTriggerFor]="menu" id ="subMenuBtn" [class.full-opacity]="getNodeResult(node).highlight" [class.highlight]="text.highlight" matTooltip="Search o ...

What is the best way to center align the placeholder in an ion-input field?

What is the best way to center align the placeholder in ion-input? Here's a screenshot of my current ionic input fields with left alignment. I've attempted to move the alignment to the center, but I've been unsuccessful. Can someone please ...

How can I get video playback in IOS to work with Videogular2 using HLS?

I recently integrated videogular2 into my Angular 6 app to display HLS streams. Everything seems to be working smoothly on desktop and Android devices, but I encountered an error when testing on IOS: TypeError: undefined is not an object (evaluating &apos ...

Challenges arise with data updating following a mutation in @tanstack/react-query

As I work on building an e-commerce website using React, I have a specific feature where users can add products to their favorites by clicking a button. Following this action, I aim to update the profile request to display the user's information along ...

I am interested in adding a personalized icon to the progress bar in Material-UI

I am currently using the MUI linerProgressBar design. I would like to incorporate a custom UI Icon that moves along with the progress. Are there any examples of this available? I have searched for one in MUI but haven't found anything. If you know of ...

As I work on creating a jest snapshot test, I've encountered an issue with TypeScript error while using Redux within the component

Hi, I'm currently working on snapshot testing in Jest with TypeScript and React.js. The component is fetching state from the Redux store, so I've set up a mock store with all the initial states provided. However, the test is failing and the error ...

Implementing Dynamic Updates to a Google Sheets Custom Menu using Typescript

How to Automatically Update a Custom Menu in Google Sheets using Typescript I have successfully set up the following: Dynamically Updating Custom Menu of Google Spreadsheet using Google Apps Script, a demonstration script for dynamically updating the cust ...