Error: Attempting to access properties of an undefined value (specifically 'and') while utilizing an observable

My profilecomponent is designed to receive user data from a service in the form of an Object

 public profiles$: Observable<IPerson>;

  constructor(private router: Router, private userService: UserService) {}

  ngOnInit(): void {
    this.profiles$ = this.userService.getUser();
    console.log(this.profiles$);
  }

Now, I am trying to create a karma test to ensure that the data is being received properly. However, I encounter an error stating TypeError: Cannot read properties of undefined (reading 'and')

  beforeEach(async () => {
    const UserServiceSpy = jasmine.createSpyObj(['getUser']);
    UserServiceSpy.getUser().and.returnValue();
    await TestBed.configureTestingModule({
      declarations: [ProfileComponent],
      providers: [
        {
          provide: UserService,
          useValue: UserServiceSpy,
        },
      ],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(ProfileComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

It seems that the error is originating from this line of code: UserServiceSpy.getUser().and.returnValue();

However, I am confused as getUser already returns an observable. There should be no need for of()

 getUser(): Observable<IPerson> {
    let data: any = localStorage.getItem(this.storageID);
    return of(JSON.parse(data));
  }

Answer №1

It seems your spy creation is not quite right:

Try using jasmine.createSpyObj('UserService', ['getUser']);

Make sure to pass the object name as the first parameter and an array of methods to spy on as the second parameter when using the createSpyObj function

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 2 - Error: Module ""."" not found at runtime

Encountered a perplexing error while running my Ionic 2 application on localhost using the command: ionic serve I've diligently inspected all my imports for any incorrect paths in my TypeScript files, but haven't found anything amiss. The only ...

Tips on sending component values to Host Listener in Custom Directives using Angular 2

I am looking to transmit model values from my HTML template to a custom directive: @Directive({ selector: '[eventlistener]' }) export class EventListener { @Input() value:string = 'Not Defined'; @HostListener('click& ...

Ways to align the label at the center of an MUI Textfield

My goal is to center the label and helper text in the middle of the Textfield. I managed to achieve this by adding padding to MuiInputLabel-root, but it's not responsive on different screen sizes (the Textfield changes size and the label loses its cen ...

How can you navigate to a particular page within a Single Page Application using NodeNS?

My NodeJS server is hosting a single page application that was built using Angular5. In certain circumstances, I need to direct users to a specific page within the application. For instance, during a designated time period, I want users to be redirected t ...

Deduce the Prop Component Type by Examining the Attribute Type

I am facing an issue with a component that requires a `labels` attribute. <Component defaultValue={FURNITURE.BED} labels={[ { value: FURNITURE.BED, text: 'Bed', }, { value: FURNITURE.COUCH, text: 'C ...

Errors arose due to the deployment of TypeScript decorators

Using TypeScript in a brand new ASP.NET Core project has brought some challenges. We are actively incorporating decorators into our codebase. However, this integration is causing numerous errors to appear in the output of VS2015: Error TS1219 Experim ...

Angular: Determining when a form has returned to its original state

My current task involves working with a reactive form that comes with default values. I need to figure out how to prevent the user from saving changes until they have modified something, and then revert back to the initial state. Although I can subscribe ...

Issue with memory leakage detected during compilation of Angular 12 application

My coworker and I are currently in the process of optimizing our Angular 12 application for our enterprise. The Issue: One major challenge we have encountered while developing our application is the continuous increase in memory usage each time the angul ...

Running into a glitch while trying to npm install the Angular 2 quickstart project

Having trouble installing the dependencies for this repository. The issue arises during the postinstall script while trying to run the typings install command The error message displayed is: typings ERR! message Unable to read typings for "es6-shim". Yo ...

Ways to make the input field appear invalid without the use of forms, causing the bottom outline to turn red when a specific condition is met

Currently, the application does not utilize any forms. I am interested in making the input field invalid under certain conditions within the component. For example, if a user leaves the input field blank, I would like the bottom outline to turn red when an ...

Testing React Hooks in TypeScript with Jest and @testing-library/react-hooks

I have a unique custom hook designed to manage the toggling of a product id using a boolean value and toggle function as returns. As I attempt to write a unit test for it following a non-typescripted example, I encountered type-mismatch errors that I' ...

Unable to transmit props while employing Typescript in ReactJS

Attempting to pass props from components like AllProducts, MenProducts, etc. to the AddToCartButton component for reusability presents a challenge. When trying to pass props using: <AddToCartButton id={product.id} /> An error is encountered: Type & ...

How can you generate a "Package Contains Lower Node Version" error message during the installation of an NPM package if the node version is higher than the current system's node version?

I am looking for a way to trigger an error during the installation of an NPM package if the node version supported by that module does not match the system/server node version. Specifically, I want to prevent the installation of any npm module that suppor ...

Using the recommended Prettier plugin for TypeScript in ESLint is causing issues with the ability to use the override keyword

Software Versions: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a0f190603041e2a5d445958445a">[email protected]</a> <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7000021504041915023 ...

Ignore verification of unused parameters

In my typescript project compilation process, I make use of the noImplicitAny option to ensure that I specify the types for variables and arguments. However, there are instances where I have unused arguments. For instance: jQuery.ajaxTransport("+*", func ...

TypeScript: Defining an Array Type within a Namespace or Module

Within a specific namespace, I have the following code: const operation1 = Symbol("operation1"); const operation2 = Symbol("operation2"); export interface Array<T> extends IConjable<T>, ISeqable<T> {} Array.prototype[op ...

Troubleshooting: Angular 2 property binding animations not functioning as expected

I'm attempting to create a fade-in animation for a div element. Here is the code snippet: import { Component, trigger, state, style, transition, animate, keyframes, group } from '@angular/core'; @Component( ...

Discovering how to specify the type of a dynamically created object using 'for await' in TypeScript

for await (user of users) { ... } Encountered an issue: "error TS2552: Cannot find name 'user'. Did you mean 'users'?" Appreciate your assistance. ...

Issue with importing Control in Ionic 2 leads to errors

I am encountering an issue when trying to import Control for email Validator in my Ionic 2 RC0 project. Below is the code snippet: /** * Created by adirz on 10/14/2016. */ import { Control } from '@angular/common'; export class EmailValidator ...

Using ES6 Template Strings for Template Binding in Angular 4

There's something I was able to easily accomplish in Vue, but for some reason, it doesn't seem to work in Angular 4: <div class="time-translate" [ngStyle]="{transform: `translate3d(${gridTranslateX}px, 0, 0)`}"> It appears that I may have ...