the undefined 'pipe' cannot be read

Trying to perform unit testing for an Angular component is a new experience for me. Currently, I am encountering a specific issue that I would like assistance with.

The component in question contains the following select statement:

this.store.select(getInfo)
    .pipe(takeWhile(() => this.isLive)
    )
    .subscribe((data) => {
      this.text = data;
    }); 

The unit test case I have set up looks like this:

fdescribe(‘TestComponent', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>; 

  const testStore = jasmine.createSpyObj('Store', ['select']);

  beforeEach(async(() => {

    TestBed.configureTestingModule({
      declarations: [TestComponent],
      imports: [MaterialModule, FiltersModule],
      providers: [
        {provide: Store, useValue: testStore }],

      schemas: [NO_ERRORS_SCHEMA]
    })

      .compileComponents();
  }));

  beforeEach(() => {

    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

  });

  it('should create Test component', async() => {
    let initialState = {
         data: {
    “name: “xyz”,
    “age” : 20
    },
      info: [1]
    };

    testStore.select.and.returnValues(
       of(initialState.info)
     );
     fixture.detectChanges();
     await fixture.whenStable();
    expect(component).toBeTruthy();
  });
  it('should have at least 1 info’, async() => {
    let initialState = {
         data: {
    “name: “xyz”,
    “age” : 20
    }, 
      info: [1]
    };

    testStore.select.and.returnValues(
       of(initialState.info)
     );

    fixture.detectChanges();
    await fixture.whenStable();

    console.log("text is ",component.text);
    });

});

This test is quite basic as I am still learning how to write more complex tests. The error message I encounter states: "TypeError: Cannot read property 'pipe' of undefined", and interestingly, this only occurs for the 'should create Test component' test case. I am uncertain about the cause of this issue.

I appreciate any guidance on where I may be making a mistake.

Answer №1

When providing a service, each test receives its own copy of the provided object. In this situation, you are assigning the value of testStore.select to the original object within the test itself. You have two possible solutions.

const service = TestBed.get(Store) as Store;
service.select = jasmine.createSpy('select').and.returnValue(of(info));

The first option is to set testStore.select immediately after declaring the Jasmine spy in your beforeEach function. The second option involves obtaining a reference to your testStore within the test and then assigning to it.

The choice between these options depends on your specific needs. If there is no call to a component method and you are assuming that the code shown is called from ngOnInit, then the first option may be simpler to implement.

If you wish to customize what info looks like for each test, you can opt for the second approach. This would involve either calling component.onInit() after setting the select method's return value or delaying the first fixture.detectChanges until after setting the select. In this case, you would remove fixture.detectChanges from your beforeEach function.

In most cases, async or whenStable will not be necessary for this setup to function correctly.

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

Searching function in material-table does not work properly with pipe symbol

Within my data table, I utilize the @pipe to display name instead of position in the position row... The name is sourced from a separate JSON file... <ng-container matColumnDef="position"> <mat-header-cell *matHeaderCellDef> No. </ma ...

Enhance the functionality of Immutable.js field by integrating a custom interface in Typescript

Imagine a scenario where the property name is field, essentially an immutable object. This means that methods like field.get('') and other immutable operations are available for use. Nevertheless, I have my own interface for this field which may ...

Encountering a promise error when using TypeScript and React Lazy

I've been working with React and TypeScript, incorporating a higher order component to verify user authentication. However, after implementing the hoc, I encountered an error in my routes: /home/nidhin/Documents/Nidhinbackup/F/iot-remsys-demotwo/rem ...

Tips for formatting a Date field within an Angular application

After receiving a stringVariable from the backend service, I successfully converted it into a Date field with the following code snippet. date d = new Date(stringVariable ); While this conversion worked fine, the resulting date format is not what I requ ...

The compatibility issue between the text-mask library and the Angular material datepicker is causing functionality problems

I am currently utilizing the text-mask library (https://www.npmjs.com/package/angular2-text-mask) in an attempt to integrate it with two Angular datepicker components. The functionality works as expected when manually entering the date into the input field ...

Unable to input text in an Angular2 input field

Encountering an issue with users on Windows 7 using IE11 while trying to input information into textboxes or textareas. The drop-downs and checkboxes are functioning properly, but additional fields cannot be filled out even after toggling visibility with t ...

Setting Values in Angular Reactive Forms Programmatically

I am working on an Angular Reactive Form that includes validation. I need assistance with properly calling the setter for my hiddenComposedField. app.component.ts ngOnInit() { this.myForm = this.formBuilder.group({ 'field1': ['' ...

Combining Data in Angular and Firestore: Exploring the Power of Observables

I am attempting to retrieve a profile document using valueChanges and combine it with session data. However, when I utilize forEach, the observable returned is null (I'm still new to both technologies). The following code successfully re ...

Next.JS-13 has encountered an inappropriate middleware in its App Based Routing functionality

I am currently working on developing a user authentication system that includes features for Login, Signup, and Logout. As part of this project, I have created a middleware.ts file in the src directory, which is located next to the app directory. Below is ...

Typescript declaration for a .js file in a diverse project

Hey there! I'm currently in the process of converting my JavaScript React Redux project to TypeScript, and I've decided to kick things off by tackling my redux reducers file. Here's a snapshot of how my project is structured: Project/ .. ...

How to extract key-value pairs from an object in a TypeScript API request

I am trying to extract the data '"Cursed Body": "100.000%"' from this API response using TypeScript in order to display it on an HTML page. Can anyone help me figure out how to do this? API Response { "tier": &q ...

Error message: "ExpressionChangedAfterItHasBeenCheckedError - encountered while using ngIf directive to hide/show a progress

My HTTP interceptor is set up to display a loading bar whenever an HTTP request is made: intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const dataStorageService = this.injector.get(DataStorageService); ...

Setting a timeout from the frontend in the AWS apigClient can be accomplished by adjusting the

I am currently integrating the Amazon API Client Gateway into my project and I have successfully set up all the necessary requests and responses. Now, I am trying to implement a timeout feature by adding the following code snippet: apigClient.me ...

What are effective strategies for troubleshooting Dependency Injection problems in nest.js?

Can someone explain the process of importing a third-party library into NestJS using Dependency Injection? Let's say we have a class called AuthService: export class AuthService { constructor( @Inject(constants.JWT) private jsonWebToken: any, ...

Encountering issues with installing angular/cli due to errors popping up

When attempting to install Angular in my terminal after completing the setup, I encountered the following error message: I have already installed: Node v6.10.3 npm ERR! Darwin 17.7.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g ...

Exploring the versatility of Highcharts with callback functions and comprehensive

Currently, I am utilizing Highcharts with angular 9. Here is the link to the code : https://stackblitz.com/edit/angular-ivy-wdejxk For running on the application side or test side, follow these instructions: Test Side: In the angular.json file at line ...

The readonly property of the ng2-currency-mask <input> element is not functioning properly

Seeking assistance with an input field that requires users to enter monetary values. I am utilizing ng2-currency-mask for this purpose, but I also need the input to be read-only. Adding the readonly attribute did not resolve the issue as the value still ch ...

Establish the predefined date for the air-datepicker

I am currently utilizing the air-datepicker inline feature. My objective is to establish the starting date for it. Below is the script detailing my attempt: export function load_datepickers_inline():void { const search_legs_0_datepicker = $("#search_leg ...

Using a Typescript typeguard to validate function parameters of type any[]

Is it logical to use this type of typeguard check in a function like the following: Foo(value: any[]) { if (value instanceof Array) { Console.log('having an array') } } Given that the parameter is defined as an array o ...

Utilize Angular 2 with Google Maps Places Autocomplete to dynamically update an input field with location suggestions [DOM manipulation]

Recently, I have been utilizing the "Angular 2 + Google Maps Places Autocomplete" search functionality. Essentially, it involves an input field that looks like this: <input placeholder="search your location" autocorrect="off" autocapitalize="off" spell ...