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

Developing a search feature using Angular 6 with Observable subscription for the FrontEnd application

I have a unique challenge where I need to implement a full text search in the FrontEnd due to restrictions with the API. When the frontend starts up, it fetches all data entries from the Backend and subscribes them inside a component using an async pipe. T ...

Error message displaying 'class-transformer returning undefined'

I'm new to working with the class-transformer library. I have a simple Product class and JSON string set up to load a Product object. However, I'm encountering an issue where even though I can see the output indicating that the transformation was ...

Issue TS2769: No matching overload found for this call. The type 'string | null' cannot be assigned to type 'string | string[]'

export class AuthService { constructor(private http: HttpClient, private webService: WebRequestService, private router: Router) { } login(email: string, password: string) { return this.webService.login(email, password).pipe( shareReplay(), ...

issue with mongoose virtual populate (unable to retrieve populated field)

During my project using mongoose with typescript, I encountered an issue with adding a virtual called subdomains to populate data from another collection. Although it worked without any errors, I found that I couldn't directly print the populated data ...

Should the User Id be retrieved within the ngOnIt() function?

Is it considered incorrect to access the User Id within the ngOnIt() method using this.afAuth.auth.currentUser.uid;? I am encountering an issue where uid is undefined when I reload the page, although it works correctly after logging in or being redirect ...

In search of a practical and functional demonstration showcasing Electron v8 combined with TypeScript

Excuse the straightforwardness of my inquiry, as I am reaching the limits of my patience. I am in search of a practical example demonstrating the use of Electron v8 and TypeScript. The example should be simple and functional, without the need for WebPack, ...

You cannot assign void to a parameter expecting a function with no return value

I have been working on an angular application that was initially developed in Angular 2, then upgraded to versions 7 and 9, and now I'm attempting to migrate it to Angular 11. There is a function in my code that fetches the notification count for the ...

Is it possible to loop through each row in a table using Cypress and execute the same actions on every iteration?

I have a frontend built with html/typescript that features a table of variable length containing action buttons in one of the columns. I am looking to create a Cypress test that will click on the first button of the first row, carry out a specific task, an ...

How can I implement a feature in Angular where clicking the edit button loads a form (in a separate component) pre-populated with previous data, along with an update button for

Within the employee-list component, there is a table displaying a list of employees. This table includes an option to edit details. <button type="button" class="btn btn-primary" routerLink="../create-employee">Edit</b ...

Tips on personalizing the formatting alert in Webclipse for Angular 2 using Typescript

Webclipse offers extensive formatting warnings for TypeScript code, such as detecting blank spaces and suggesting the use of single quotes over double quotes. However, some users find the recommendation to use single quotes annoying, as using double quotes ...

transformation of categorized unions in software development

Experimenting with routing-controllers and its built-in class-transformer feature, I tried creating an interface for executing a search query based on either a location id or location coordinate. My aim was to utilize a discriminated union as a body parame ...

The module named "mongoose" does not have any member called 'PaginateResult' exported

I'm facing an issue while trying to add the necessary types for "mongoose-paginate" in my Angular 4 project setup with "angular-cli". The problem arises when Webpack throws an error. import {PaginateResult} from "mongoose"; ... getAll(page: number) ...

FilterService of PrimeNg

Looking for assistance with customizing a property of the p-columnFilter component. I have managed to modify the filter modes and customize the names, but I am having trouble with the no-filter option. Has anyone found a solution for this? this.matchMo ...

Unable to apply styling to table cells that are dynamically added using JQuery within an Angular

Currently working on setting up a form using Angular. Within the hotel.view.html file, there is a table that looks like this: <table id="rooms"> <tr> <td>Room Type</td><td>Beds</td><td>Q.ty</td ...

Angular 2 AOT implementation with External Dependencies

Utilizing Highcharts and Kendo Charts within my angular 2 application, I encountered issues during AOT compilation such as Cannot Import Module or HomeModule' is not exported by or Cannot Determine Module .. It has been suggested that I should i ...

Styling Based on Conditions in Angular

Exploring the unique function of conditional formatting in Microsoft Excel, where color bars are utilized to represent percentages in comparison to the highest value. Is there a way to replicate this functionality using HTML5 with CSS or JavaScript? Perha ...

Using TypeScript to declare ambient types with imported declarations

In my TypeScript project, I have a declaration file set up like this: // myapp.d.ts declare namespace MyApp { interface MyThing { prop1: string prop2: number } } It works perfectly and I can access this namespace throughout my project without ...

What could be causing the failure of the subscribe function to interpret the API response

I want to retrieve user information by using their identification number through a method component.ts identificacion:any = this.route.snapshot.paramMap.get('identificacion'); constructor(private route: ActivatedRoute, private dataService: ...

The hidden pop-up window from a particular tool is currently not being displayed

I attempted to upload my code onto Stackblitz in search of assistance with my dynamic modal not displaying. I am working on a function that I intend to be able to call from any component to create a popup where I can dynamically modify the header, body, an ...

Display the first item last in an *ngFor loop in Nativescript Angular

I'm facing some confusion with the sorting of an array in JavaScript. Although the index, last, and first seem to be correct, the result is not as expected. Versions @angular/core: 4.1.0 nativescript-angular: 3.1.3 typescript: 2.4.0 Expected 1234 ...