Error: Attempting to access the 'returnValue' property of an undefined variable

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ProductListComponent } from './product-list.component';
import { FormsModule } from '@angular/forms';
import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';
import { ProductService } from './product.service';

describe('ProductListComponent', () => {
  let component: ProductListComponent;
  let fixture: ComponentFixture<ProductListComponent>;
  let debugElement: DebugElement;
  let productService: ProductService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ProductListComponent ],
      imports: [FormsModule],
      providers: [ProductService]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ProductListComponent);
    productService = TestBed.get(ProductService);
    component = fixture.componentInstance;
    fixture.detectChanges();
    debugElement = fixture.debugElement;
  });



  fit('should test the product list filtering functionality (done)', (done)=> {
    //component.searchText='fresh';
    let productSpy = spyOn(productService, 'filterProductList').withArgs('fresh').and.callThrough();


    productSpy.calls.mostRecent().returnValue.then(()=>{
      fixture.detectChanges();
      const value = debugElement.query(By.css('#product_0')).nativeElement.innerText;
      expect(value).toContain(component.searchText);
      done();
    });


  });

});

I am currently working on a testing scenario for filtering the product list based on a search term. Although I have set up a spy for the ProductService, an error is encountered:

TypeError: Cannot read property 'returnValue' of undefined

This issue arises when trying to access the following line of code:

productSpy.calls.mostRecent().returnValue.then

Even after conducting online research, a suitable solution could not be found.

The service that this test case is meant to validate includes the following method: 1. filterProductList - This function receives a string parameter and filters the list of products to return the matching product.

@Injectable({
  providedIn: 'root'
})
export class ProductService {
  productList = PRODUCT_LIST;

  constructor() { }
  public getProductList(){
    return of(this.productList);
  }

  public filterProductList(searchString: string): Promise<any>{
    let dataObs: Observable<any>;
    //dataObs = of(this.productList.filter( product => product.title.toLowerCase().indexOf(searchString) > -1));
    //setTimeout(()=> { dataObs = of(this.productList.filter( product => product.title.toLowerCase().indexOf(searchString) > -1))},1000);
    return of(this.productList.filter( product => product.title.toLowerCase().indexOf(searchString) > -1)).toPromise();
  }
}

export const PRODUCT_LIST = [{
  "title": "Brown eggs",
  "type": "dairy",
  "description": "Raw organic brown eggs in a basket",
  "filename": "0.jpg",
  "height": 600,
  "width": 400,
  "price": 28.1,
  "rating": 4
}];

Answer №1

After some trial and error, I finally managed to figure out why the method being spied on was not getting called.

fit('should test filter product list (done)', (done) => {
component.searchText = 'fresh';
let productSpy = spyOn(productService, 'filterProductList').withArgs('fresh').and.callThrough();

 **component.filterProductList({});**

productSpy.calls.mostRecent().returnValue.then(() => {
     fixture.detectChanges();
     const value = debugElement.query(By.css('#product_0')).nativeElement.innerText;
     expect(value).toContain(component.searchText);
     done();
   });
 });

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

The type 'string' cannot be utilized to index type

Apologies for adding yet another question of this nature, but despite finding similar ones, I am unable to apply their solutions to my specific case. Could someone please assist me in resolving this TypeScript error? The element implicitly has an 'an ...

What is the best way to use a generic callback function as a specific argument?

TS Playground of the problem function callStringFunction(callback: (s: string) => void) { callback("unknown string inputted by user"); } function callNumberFunction(callback: (n: number) => void) { callback(4); // unknown number inputt ...

Encountering a premature closure error, specifically the inability to set headers after they have already been sent to the client, when trying to stream video

I am in the process of constructing a video streaming web server with Nestjs. I have diligently followed the steps outlined in the Nest documentation. Unfortunately, I encountered some errors... MY file.controller.ts import { Controller ...

Tips on hiding the menu toggler in PrimeNg

Struggling with PrimeNg implementation in my Angular project, I am unable to find a simple solution to hide the menu toggler. Allow me to illustrate my current setup in the first image and what I desire in the second. Let's dive in: View First Image ...

What is the most effective way to sort a list using Angular2 pipes?

I'm currently working with TypeScript and Angular2. I've developed a custom pipe to filter a list of results, but now I need to figure out how to sort that list alphabetically or in some other specific way. Can anyone provide guidance on how to a ...

Every time I attempt to install a package, I encounter an NPM unmet peer dependency issue

Entering the complex world of NPM for the first time has been quite a challenge. After running create-react-app, the installation process is almost complete except for some warning messages: yarn add v1.17.3 [1/4] Resolving packages... warning react-scri ...

Having trouble with the customValidator in SingleSelect editor of Angular Slickgrid not working as expected

My current setup involves using angular-slickgrid with the Editors.singleSelect inline editor enabled for a cell. I am looking to validate the selected dropdown value based on certain conditions. I tried creating a custom validator following the example pr ...

Retrieve the array from within the string

Any suggestions on how I can extract the array from this string? The current string is: "['Biller.Customer.Data@Taxonomy', 'Product.Platform and Enterprise Services Data.Data@Taxonomy']" I need to extract it to look like thi ...

Angular dependencies running on GitLab's CI/CD pipeline

I am interested in setting up a runner that can automatically build and deploy an Angular application. This requires installing the project dependencies using npm install before the building or deploying process, as these dependencies are not stored in the ...

Angular Error: Trying to access property "name" of an undefined object

In my Angular 4 project, I keep encountering a strange error every time my sidebar component is rendered. There is no "name" attribute in my code, so I am having difficulty understanding why this error is occurring. Below is the console error log. Any assi ...

Is there a way I can utilize the $timeout and $interval functionalities that were implemented in angular.js, but for the Angular framework?

When working with Angular.js, I made use of the $timeout and $interval functions (which are similar to setInterval and setTimeout in JavaScript). $timeout(function(){}) $interval(function(){},5000) To stop the interval, I utilized $interval.cancel($scop ...

Reduce the size of the JSON file located in the Assets folder during an Angular build

What is the most effective method to compress JSON files in an Angular production build? I currently have a JSON file in the assets folder that remains unchanged when the production build is completed. During development, the file appears as the Developme ...

Leverage a provider implementation within another implementation of the same provider in Angular

Is it possible to inject one provider implementation into another implementation of the same provider in Angular? I have been unable to achieve this so far. The goal is to be able to customize the second implementation using data from the first implementat ...

Encountering difficulty retrieving host component within a directive while working with Angular 12

After upgrading our project from Angular 8 to Angular 12, I've been facing an issue with accessing the host component reference in the directive. Here is the original Angular 8 directive code: export class CardNumberMaskingDirective implements OnInit ...

What steps can I take to ensure my dynamic route functions correctly in NextJs?

// /home/[storeId]/layout.tsx import prismadb from "@/lib/prismadb"; import { auth } from "@clerk/nextjs/server"; import { redirect } from "next/navigation"; export default async function DashboardLayout({ children, params, ...

Is there a way to automatically close a p-dropdown when a p-dialog is closed?

One issue I have encountered with my angular component, which includes ngprime p-dialog, is that the p-dropdown within the dialog does not close properly when the user accidentally clicks on closing the dialog. This results in the dropdown options remainin ...

Dynamic typing depending on the individual elements within an array

I am working with some extensions: type ExtensionOptions = { name: string } type BoldOptions = ExtensionOptions & { boldShortcut?: string } type ItalicOptions = ExtensionOptions & { italicShortcut?: string } type LinkOptions = ExtensionOptions &am ...

`Why are some options missing from the "New Item" feature in Visual Studio?`

Recently, I started a Cordova project using Visual Studio 2015. To my surprise, when I attempt to add a new item by right-clicking, I am presented with only a limited number of options. For example, I wanted to add a "TypeScript json config file" (known as ...

Customize the template of a third-party component by overriding or extending it

I am facing a situation where I need to customize the template of a third party component that I have imported. However, since this component is part of an npm package, I want to avoid making direct changes to it in order to prevent issues when updating th ...

How can I transform a Firestore collection into an array?

I'm struggling with converting the data retrieved from Firestore into an array that can be used for a chart.js graph. Retrieving Data from Firestore fetchData(){ //Get data this.updatesCollection = this.afs.collection(pathStats); this. ...