Monitoring a Typescript Class's Get() or Set() function using Jasmine Spy

While working with Jasmine 2.9, I have encountered no issues spying on both public and private functions, except for when trying to spy on a get or set function at the class level.

private class RandomService {
  public dogsHealth = 0;

  private get personsFullName(): string {
    return firstName + lastname;
  }

  private set personsLocation(address: string, city: string, country: string): string {
    return address + city + country;
  }

  public get dogsFullName(): string {
    return dogFirstName + dogLastName;
  }

  public get isDogAlive(): boolean {
    return dogsHealth <= 0 ? true : false;
  }
}

I have attempted various solutions:

spyOnProperty(RandomService, 'dogsFullName', 'get').and.returnValue(true);
spyOnProperty(RandomService, 'dogsFullName').and.returnValue(true);
spyOn(RandomService, 'dogsFullName').and.returnValue(true);
spyOnProperty(RandomService.dogsFullName, 'dogsFullName', 'get').and.returnValue(true);

Despite my efforts, I have not found a solution online and will continue to search. The get or set functions create variables, so I thought solution 4 might work, but it did not.

Update

(The code above has been updated as well)

Attempting to update by returning a string and using the following jasmine method results in an error:

spyOnProperty(RandomService, 'dogsFullName', 'get').and.returnValue('Frank');

Expected a spy, but got 'Frank'

Similarly, for the function isDogAlive, I receive the following message:

<toHaveBeenCalled> : Expected a spy, but got true.

While I understand that the correct value is being returned, shouldn't it be recognized as a spy if I use spyOn?

Answer №1

If you change the return value from a boolean of true to something like "frank", it may resolve the issue. It seems that the expected return value is likely a string rather than a boolean.

let spyTemp = spyOnProperty(RandomService, 'dogsFullName', 'get').and.returnValue("frank");

Next,

expect(spyTemp).toHaveBeenCalled();

Answer №2

If you're looking for some solutions, consider these options:

spyOnProperty(RandomService.prototype, 'dogsFullName', 'get').and.returnValue('ben');

// alternatively
service = new RandomService();
spyOnProperty(service, 'dogsFullName', 'get').and.returnValue('ben');

Alternatively, if your method is a static member of the class:

export class RandomService {
  static dogFirstName: string;
  static dogLastName: string;

  public static get dogsFullName() {
    return RandomService.dogFirstName + RandomService.dogLastName;
  }
}

spyOnProperty(RandomService, 'dogsFullName', 'get').and.returnValue('ben');

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

Learn the steps to assign a Base64 URL to an image source

I am currently facing an issue with an image that is being used with angular-cli: <img src="" style="width: 120px; padding-top: 10px" alt="" id="dishPhoto"> The image has a Base64 url named imgUrl. My intention is to set the image source using the ...

Can one utilize generic parameter value within a conditional type result field in Typescript?

Trying to create a versatile function type for data transformation can be a bit tricky. When dealing with a single object, it's straightforward: export type SingleObjFunction<InputDataType, OutputDataType> = (object: InputDataType) => Outpu ...

Angular 5 ngIfElse: How to save the outcome of a condition in a storage container

Code Snippet: <mat-icon [ngClass]='{ rotate: !users }'>refresh</mat-icon> <div *ngIf="usersObservable | async as users; else loading"> ... </div> <ng-template #loading let-users> Waiting... </ng-template> ...

Using an enum with [routerlink] in Angular 7 is a great way to navigate

Enum Example: export enum InternalLinks { Home = '/home', About = '/about' } In the HTML of my CustomComponent, I have this: <div class="link-container text-right"> <a [routerLink]="InternalLinks.About" class="text-b ...

Comparing setInterval with Observable's timer method, which is the superior choice for setting up timers?

In order to create a timer in Angular, I am currently using Observable as shown below: timer: Observable<any> = Observable.timer(0, 990); timerSubscription: Subscription; this.timerSubscription = this.timer.subscribe((value) => { this. ...

Provide a string argument when instantiating an abstract class

I am searching for a method to assign a name string within a class and utilize it in the abstract class at the constructor level, without the need for a function. Opening up the constructor is not an option due to using typedi. You can access the playgrou ...

Angular, Node.js, NVM (Node Version Manager), and NPM (Node

I recently upgraded my Node version from v6.5.0 to v8.9.4 using nvm and noticed that npm also got updated to a newer version. Now, I have a few questions regarding this update: After switching to Node 8.9.4 with nvm, why does the command node -v still ...

Dealing with an `err_connection_refused` HTTP error in Angular 7: What's the best approach?

Whenever my application encounters an err_connection_refused error during an HTTP request, I need to display a message to the user. This error typically occurs when the server is disconnected. http.get().subscribe( (response) => { }, err ...

Occasionally, angulafire2's getDownloadURL() function may fail to work with Angular. Could this be due to asynchronous processes?

Receive a 404 error when trying to access . Firebase is reporting a download link error with the following message: "Firebase Storage: Object 'hw04.docx' does not exist." Below is the code snippet related to this issue. upload(event) { cons ...

Locate and refine the pipeline for converting all elements of an array into JSON format using Angular 2

I am currently working on implementing a search functionality using a custom pipe in Angular. The goal is to be able to search through all strings or columns in a received JSON or array of objects and update the table accordingly. Here is the code snippet ...

I am interested in transforming an Angular 2 observable into a custom class

Having recently delved into the world of angular2, I've spent countless hours trying to tackle a particular challenge without success. My goal is to convert an observable from an HTTP call and store it in a class. Below are the key components involve ...

Encountered an HttpErrorResponse while trying to access the API endpoint

I am encountering an issue when trying to update and insert data with a single post request. https://i.sstatic.net/T9UKR.png Below is my API code: https://i.sstatic.net/kkwqs.png Here is the service code: https://i.sstatic.net/IUMSd.png This section ...

Typescript React: Implementing type definitions for JSS classes object

Here is the react code I am working with: import React from 'react'; import withStyles from "react-jss"; const styles = { box: { border: "2px solid #000" } }; interface ComponentProps {} class Welcom ...

Is there a solution for the error "Unable to persist the session" in a Next.js application that utilizes Supabase, Zustand, and Clerk.dev for authentication?

I have successfully set up a Next.js application with Clerk.dev for authentication and Supabase for data storage. I'm also leveraging Zustand for state management. However, an error is plaguing me, stating that there's "No storage option exists t ...

Angular - Set value on formArrayName

I'm currently working on a form that contains an array of strings. Every time I try to add a new element to the list, I encounter an issue when using setValue to set values in the array. The following error is displayed: <button (click)="addNewCom ...

When attempting to compile the building project following the upgrade to Angular 9, an error message is displayed stating "Unable to access property 'length' as it is undefined

I'm currently in the process of updating my Angular 9 project by following the migration guide on update.angular.io. After running ng update @angular/core @angular/cli, I encountered an error "ERROR in Cannot read property 'length' of undefi ...

A simple way to automatically fill an input field with a mask when clicking in Angular 2

When a user clicks on this span, the following action is triggered: <span data-content="15" #Fast15 (click)="enterFastTime(Fast15)" class="quick-time">15mins</span> Users can also manually input a date in the following input field. If they ...

Creating an Escape key press event in plain Typescript without using JQuery

Is there a way to trigger an Escape button press event in Angular unit tests? const event = document.createEvent('UIEvent'); event.initUIEvent('keydown', true, true, window, 0); (<any>event).keyCode = 27; (<any ...

Having trouble fetching information from a JSON file stored in a local directory while using Angular 7

I am currently experiencing an issue with my code. It works fine when fetching data from a URL, but when I try to read from a local JSON file located in the assets folder, it returns an error. searchData() { const url: any = 'https://jsonplaceholde ...

The call to react.cloneElement does not match any overloads

I'm encountering a typescript error in my React code when using React.cloneElement with the first parameter "children", and I am unsure of how to resolve it. As a newcomer to typescript, I believe that the type definitions in index.d.ts for cloneElem ...