Experimenting with a TypeScript function containing a subscription operation

Currently, I am experimenting with Jasmine/Karma while working on an Angular 4 project. The issue I'm facing involves testing a function that seems to have trouble setting the 'name' property:

https://i.stack.imgur.com/3q49i.jpg

The assignment of this.name appears to be untouched. Here are the different approaches I've attempted so far:

it('should make sure name is set', () => {
  component.retrievePageInfo();
  expect(component.name).toBeDefined();
});

Unfortunately, at this point in time, 'name' remains undefined. I also tried:

it('should make sure name is set', () => {
  component.retrievePageInfo().subscribe(art => {
    expect(component.name).toBe(art["name"]);
  });
});

However, this led to the error "Property 'subscribe' does not exist on type 'void'." Modifying the function like this:

retrievePageInfo() {
  return this.httpClient.get("/api/art/" + this.art_id)
  .subscribe(art => {
    this.name = art['name'];
  });
}

Brought the error "Property 'subscribe' does not exist on type 'Subscription'." even though subscribe is necessary here.

I would greatly appreciate some guidance on how to overcome this hurdle!

Edit: I'd find a basic example helpful since my attempts so far haven't been successful. My current approach involves splitting the function into one that returns an observable and another that utilizes it, but my tests continue to fail to capture the desired outcome.

Edit: In my latest try, I have imported fakeAsync and tick

it('should set name value', fakeAsync(() => {
    expect(component.name).toBeUndefined();
    spyOn(component, "retrievePageInfo");
    component.retrievePageInfo();
    tick();
    fixture.detectChanges();
    expect(component.name).toBeDefined();
}));

Yet, despite these efforts, the failure persists with "Expected undefined to be defined."

Answer №1

Exploring async unit testing is essential:

 it('#getObservableValue should retrieve value from observable',
    (done: DoneFn) => {
    service.getObservableValue().subscribe(value => {
      expect(value).toBe('observable value');
      done();
    });
  });

The snippet shown above can be found in the documentation: https://angular.io/guide/testing#service-tests

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

Implementing Bootstrap 4 in an Angular 9 project without the use of JQuery

Currently, I am actively working on detaching all JQuery dependencies within my Angular project. Most of the dependencies stem from utilizing Bootstrap 4 components. Eliminating dropdowns and removing all instances of data-*** seemed to help in this proc ...

Incorporate my personalized icons into the button design of ionic 2 actionSheet

I'm struggling to figure out how to incorporate my personal icon into the actionSheet feature of ionic 2/3. presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Mode', buttons: [ { ...

Utilizing the backtick operator for string interpolation allows for dynamic value insertion

Greetings! Currently, I am delving into the world of Angular 2 and have stumbled upon some interesting discoveries. To enhance my knowledge of TypeScript, I decided to utilize the ScratchJS extension on the Chrome browser. During this exploration, I experi ...

Exploring ways to incorporate conditional imports without the need for personalized webpack settings!

Our project is designed to be compatible with both Cordova and Electron, using a single codebase. This means it must import Node APIs and modules specific to Node for Electron, while ignoring them in Cordova. Previously, we relied on a custom webpack con ...

Three.js functions smoothly on both Android devices and desktop computers using Chrome, unfortunately it is not compatible with Safari

After diving into learning three.js, I decided to incorporate it into my angular 11 project. I created a simple demo using a SphereBufferGeometry and deployed it on github pages. Surprisingly, when I accessed it on an android phone, everything worked perfe ...

Angular 10 introduces a new feature where BehaviorSubject can now hold and emit two

Currently, I am attempting to log in using Firebase. The login system is functioning correctly; however, I am facing a challenge in retrieving the error name from the authentication service and displaying it in my login component. SignIn(email: string, pas ...

Using parameters to create unions in TypeScript

Is there a standard method to parametrically define a union? I'm searching for a way to generically define something like: type U<K> = T<K1> | T<K2> | ... | T<Kn> // Where K === (K1 | ... | Kn) Note: I'm encountering a s ...

Master your code with Rxjs optimization

Looking at a block of code: if (this.organization) { this.orgService.updateOrganization(this.createOrganizationForm.value).subscribe(() => { this.alertify.success(`Organization ${this.organization.name} was updated`); this.dialogRef.close(true ...

issue with Angular: Unable to set both minimum and maximum values in the same input field for date type

I have been attempting to apply minimum and maximum values to an Angular code snippet, here is what I have: <input type="date" class="form-control" style="width: 30%" [disabled]="!dateSent" min="{{dateSent|date:&apo ...

Can anyone provide guidance on creating a new type in Ionic Vue?

How can I define the description as a type in my code? When I run it, I get an error that says "Property 'description' does not exist on type '{ takePhoto(): Promise; }'" <script lang="ts"> import { IonPage, ...

Ways to ensure that DOM elements have completed rendering in Angular 2 Unit Tests

I am currently working on a test that focuses on an HTML element, sets its value, and triggers the blur event handler. The blur event is supposed to initiate a validation check which, if invalid, should disable a save button. During a test run, this proce ...

Having trouble locating the export in the TypeScript module

Having a situation where there is a file with an exported object: let btypes:{[key:string]:any} = { "key1":val, //... } export {btypes} I even attempted to use export default btypes Upon importing it using: import {btypes} from "../types& ...

Is it possible to eliminate the table borders and incorporate different colors for every other row?

Eliminating the table borders and applying color to alternate rows. Check out my code snippet: https://stackblitz.com/angular/dnbermjydavk?file=app%2Ftable-overview-example.ts. ...

The parent DIV has a height of 0px, yet the child element is still visible

As I explored options for creating a navbar drop down menu with an accordion effect, I stumbled upon this informative YouTube video. The tutorial demonstrated the use of a custom component and manipulation of the max-height property of the card-content ele ...

Steps for selectively targeting and updating a group of properties in a TypeScript class

Is there a way to consolidate this code into one function that can handle all the tasks below? I'm adding more text here to meet the requirements and hoping for a solution. Thank you! TypeScript is an amazing language that differs slightly from JavaS ...

Leveraging Angular, ExpressJS, and NodeJS to enable users to download a text file by simply clicking a

My goal is to incorporate a download button that allows users to download a document from my node.js server. Behold the stylish download button: https://i.sstatic.net/s4CjS.png My tech stack includes Angular for the front-end and node.js along with exp ...

Tips for repeatedly clicking a button over 50 times using Protractor

Is it possible to click the same button more than 50 times using a loop statement in Protractor? And will Protractor allow this action? Below is my locator : var nudge= element(by.xpath("//a[@class='isd-flat-icons fi-down']")); nudge.click(); ...

Issue encountered during the installation of angular2 cli

I'm currently setting up angular2 on my Linux machine, using the following command: sudo npm install -g @angular/cli After successfully installing it, I proceed with creating a new app by typing: ng new mynewapp However, when doing so, I encounter ...

Flashing issues when utilizing the Jquery ui slider within an Angular 2 component

I recently incorporated a jquery-ui slider plugin into an angular 2 component and it's been working well overall, but I have encountered an annoying issue. Whenever the slider is used, there is a flickering effect on the screen. Interestingly, when I ...

How to Retrieve the Current Item in *ngFor Loop Using TypeScript in Angular 4

In my JSON file, I have an array containing 5 people. Each person in the array has a list of items associated with them. In my HTML code, I am using *ngFor to iterate over the people and display their names. Additionally, I want to display the total sum of ...