The observed function remains untouched

In my code, I have an if condition inside a function that looks like this:

 public setOption() {
    setTimeout(() => {
    if (this.isCMode && !this.quest['isCompleted']) {
        this.toggleOption(false);
      }
},window['TIME_OUT']);

As part of testing this function, I attempted to write a jasmine test case for it as shown below:

it('should call toggleOption from setSaqOption if isTimeCompleted is false', () => {
    component.isCMode = true;
    const tSpy = spyOn<any>(component, 'toggleOption');
    component.setOption();
    fixture.whenStable().then(() => {
      if (component.isCMode && !component.quest['isTimeCompleted']) {
        expect(tSpy).toHaveBeenCalled();
      }
    });

  });

However, when running the test case, it fails and gives an error message saying "Expected spy toggleOption to have been called." Can anyone help me identify where I might be going wrong in my test case setup?

Answer №1

Try using the fakeAsync() and tick() functions to mimic time in your testing environment. The tick() function helps resolve any delays caused by the setTimeout function in the original setOption(), allowing you to check the result immediately after with fixture.whenStable().then(...).

For example:

example.component.ts:

import { Component } from '@angular/core';

window['TIME_OUT'] = 1000;

@Component({})
export class ExampleComponent {
  isCMode = false;
  quest = {
    isCompleted: false,
    isTimeCompleted: false,
  };
  public setOption() {
    setTimeout(() => {
      if (this.isCMode && !this.quest['isCompleted']) {
        this.toggleOption(false);
      }
    }, window['TIME_OUT']);
  }
  toggleOption(flag) {}
}

example.component.spec.ts:

import {
  ComponentFixture,
  fakeAsync,
  TestBed,
  tick,
} from '@angular/core/testing';
import { ExampleComponent } from './example.component';

fdescribe('65197197', () => {
  let component: ExampleComponent;
  let fixture: ComponentFixture<ExampleComponent>;
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ExampleComponent],
    });
    fixture = TestBed.createComponent(ExampleComponent);
    component = fixture.componentInstance;
  });
  it('should call toggleOption from setSaqOption if isTimeCompleted is false', fakeAsync(() => {
    component.isCMode = true;
    const tSpy = spyOn<any>(component, 'toggleOption');
    component.setOption();
    tick(1000);
    fixture.whenStable().then(() => {
      if (component.isCMode && !component.quest['isTimeCompleted']) {
        expect(tSpy).toHaveBeenCalled();
      }
    });
  }));
});

Check out the unit test result here:

https://i.sstatic.net/XszH3.png

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

Angular Material Dropdown with Option to Add New Item

Currently, I am utilizing Angular material to create a select dropdown for Religion. However, the available options may not encompass all the religions practiced worldwide. In order to account for this limitation, I aim to incorporate an "other option" tha ...

Animations in Angular fail to operate within mat-tabs after switching back when custom components are being utilized

I am facing a similar issue as Olafvv with my angular 16 project. The problem occurs in a mat-tab-group where the :enter animations do not work when navigating away from a tab and then returning to it. However, in my case, the issue lies within a custom su ...

Tips for collapsing or expanding a single button in Angular 6

I want to create rows of collapsible buttons in my code, but every time I visit the page, all the buttons are already expanded. Additionally, when I click on any button, they all expand or collapse simultaneously. HTML <div id="accordion" *ngFor="let ...

Ionic datetime returns default values upon initialization

I'm currently in the process of developing an Ionic-Angular-app. I require a datetime component on a page to set the creation date of an object. I am using formGroup for this purpose, but whenever I choose a different date, it always reverts back to t ...

Guide to adding a loading spinner into your Angular project

I've been attempting to incorporate a spinner into my application, but unfortunately, the spinner isn't showing up. Despite checking the console and terminal for errors, there doesn't seem to be any indication as to why the spinner is not a ...

Jasmine's await function often leads to variables remaining undefined

When testing a function, I encountered an issue where a variable is created and assigned a value, but the payload constant always remains undefined. campaigns-card.component.ts async ngOnInit() { const { uid } = await this.auth.currentUser const { ...

What is the proper way to add an object to an array within an object in TypeScript?

import {Schedule} from './schedule.model'; export class ScheduleService{ private schedules:Schedule[]=[ new Schedule("5:00","reading"), new Schedule("6:00","writing"), new Schedule("7:00","cleaning") ]; getSchedule(){ ret ...

Improving characteristics of an Observable Entity (Angular)

I have a question about Observables that I'm hoping someone can help me with. I am trying to work with an object that I want to turn into an Observable. Let's say the object is structured like this: export class Sample { public name: string; ...

Performing calculations on two properties of an observable object in Angular 8 and then storing the result in a new property

Looking for guidance on how to display the sum of two properties from an observable data. Take a look at the code below and let me know your thoughts: Typescript class export class Amount { Amount1: number; Amount2: number; Total:number; } In typescript ...

Understanding the Union Type in Typescript and Its Application in Angular Development

I came across this piece of code: interface Course { code: string; name: string; user: number | { id: number; name: string; }; } This indicates that a course object can contain either the user object or the user key. When fetching the cour ...

IE11 displaying corrupted characters on every JavaScript file

After attempting to add the meta charset in the html header and charset in script tag, I found that neither solution worked. I am truly puzzled by this. On a side note, the system language is set to Chinese, but changing it to English did not solve the i ...

Strategies for Implementing Pagination in an Angular 2 HTML Table Without the Use of Third-Party Tools

I have an HTML table that displays basic details along with images. I am looking to implement pagination for this table in Angular 2. Are there any alternatives to using ng2-pagination? ...

Sending a user's ID to a Bootstrap modal in Angular 4: step-by-step guide

I am currently utilizing Angular 4 for the front end and spring boot for the back end. My goal is to implement bootstrap modals to display user details when a button labeled 'user details' is clicked. This is the clients.component.html file: ...

The functionality of Angular material seems to be malfunctioning within an Angular library

After observing the potential for reusable code in my Angular projects, I decided to create a common library to streamline development. Following the steps outlined in an article (link: https://angular.io/guide/creating-libraries), I successfully created t ...

Get rid of the Modal simply by clicking on the X mark

Objective: The modal should only be closed by clicking the X mark and not by clicking outside of it. Challenge: I am unsure how to resolve this issue when using the syntax code [config]="{backdrop: 'static'}" Additional Information: I am new ...

Here's a new take on the topic: "Implementing image change functionality for a specific div in Angular 8 using data from a loop"

I need to create a list with dynamic data using a loop. When I click on any item in the list, I want the image associated with that item to change to a second image (dummyimage.com/300.png/09f/fff) to indicate it's active. This change should persist e ...

Export an array of objects using the ExcelService module

I am working with an array named listTutors that looks like this: listTutors = [{ countryId: 'tt', gender: 'both', levelId: 'tg', sessionType: 'inPerson', dashboardStatus: ['notPublished', 'p ...

Observing rxjs Observable - loop through the results and exit when a certain condition is met / encountering an issue with reading property 'subscribe' of an undefined value

I'm fairly new to working with rxjs and I've been struggling to find the right operator for what I want to achieve. Here's my scenario - I have an array that needs to be populated with results from another observable. Once this array has en ...

Encountering crashes while initializing the router in the constructor of a service in Angular 4.3

I've been scratching my head over this problem. It seems like I'm overlooking something simple. Let me show you what's inside my home.component.ts file: import { Component, OnInit } from '@angular/core'; import { AuthService } f ...

Having trouble with JSON parsing in Promise execution

I am in the process of developing a Promise with the objective of adding up any numbers discovered within an array or JSON object. The add() function is designed to receive a series of URLs as a string input and calculate the total sum of those URLs. Her ...