Anticipated that the spy would trigger an error due to the if statement being executed

I've been working on an angular 11 unit test case for code within an if block. Interestingly, when I comment out the if block, all the tests pass without any issues. However, when the if block is present, it seems that the code isn't entering the block as expected.

Here's the error message

splash-screen.service.ts

init() {
    // Retrieving the splash screen element
    this.splashScreenEl = this.document.body.querySelector('#splash-screen');
      
      this.router.events.pipe(filter((event => event instanceof NavigationEnd)), take(1)).subscribe(() => {
        setTimeout(() => {
          // Checking if the splash screen element exists...
          // Hide it upon the first NavigationEnd event
          if (this.splashScreenEl) {
            this.hide();
          }
        });
      });
  }

splash-screen.service.ts

it('should trigger hide method with end navigation event', fakeAsync(() => {
    const methodSpy: jasmine.Spy = spyOn(service, 'hide');
    eventSubject.next(new NavigationEnd(1, 'http://localhost:4200/', 'http://localhost:4200/'));
    tick();
    const splashScreenEl = jasmine.createSpy('HTML Element').and.returnValue(true);
    service.splashScreenEl = splashScreenEl;
    expect(service.splashScreenEl).toBeTruthy();
    expect(methodSpy).toHaveBeenCalled();
  }));

Any advice on how to get this test case to successfully pass would be greatly appreciated!

PS: I'm fairly new to writing jasmine test cases.

Answer №1

One must investigate the reason behind the false return of this code:

this.document.body.querySelector('#splash-screen');

To explicitly set splashScreenEl to true, follow these instructions:

it('should trigger hide method when end navigation event occurs', fakeAsync(() => {
    const methodSpy: jasmine.Spy = spyOn(service, 'hide');
    eventSubject.next(new NavigationEnd(1, 'http://localhost:4200/', 'http://localhost:4200/'));
    // include a 0 on tick to simulate 0ms passing (optional)
    tick(0);
    // add this line to manually set it to true
    service.splashScreenEl = true;
    expect(service.splashScreenEl).toBeTruthy();
    expect(methodSpy).toHaveBeenCalled();
  }));

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 mismatch issue occurs when using keyof with Typescript generics

One of the challenges I am facing is related to an interface that stores a key of another interface (modelKey) and the corresponding value of that key (value): interface ValueHolder<T, H extends keyof T> { modelKey: H; value: T[H]; } My objectiv ...

Tips for integrating Postman API with Angular 4

app.component.ts: import { Component } from '@angular/core'; import { Http, Response } from '@angular/http'; import 'rxjs/add/operator/map'; @Component({ selector: 'app-root', templateUrl: './app.component ...

Are there alternative methods for incorporating react-multi-carousel in a project utilizing NEXT.js and React/Typescript?

I installed the react-multi-carousel module and configured a simple carousel, but it's not functioning properly. The issue seems to be related to the absence of <li> tags. Here is the HTML that was rendered: <ul class="react-multi-caro ...

Delay in input bar after extensive user engagement

I've been grappling with a perplexing issue for quite some time now, and it's proving to be quite elusive. In my Angular webshop, the product overview page features a product component with a lazily loaded, highly compressed image, a title, quan ...

Is there a simpler and more refined approach for handling Observables within RxJS pipelines?

Picture this: I have an observable that gives me chocolate cookies, but I only want to eat the ones without white chocolate. Since I am blind, I need to send them to a service to determine if they are white or not. However, I don't receive the answer ...

Issue with React/Next.js input field rejecting commas

I'm experiencing a problem with an input field in my React application that was developed using Next.js. The issue arises specifically when using an iPad device, where the input field behaves inconsistently when dealing with commas. When using deskto ...

Creating a unique directive in Angular 2 with custom bindings

I have implemented a custom directive in my HTML file which displays different errorType messages for my component, msgfooter: <msgfooter [errorType]="Invalid server"> <msgfooter> or <msgfooter [errorType]="Few Parameters"> <msgfoot ...

Enforcement of static methods in Typescript abstract classes is not mandatory

In my TypeScript code, I have a simple structure defined: abstract class Config { readonly NAME: string; readonly TITLE: string; static CoreInterface: () => any } class Test implements Config { readonly NAME: string; readonly TITL ...

Issue with loading the schema in the angular.json configuration file

Encountering an issue within the angular.json file that needs attention. { "resource": "/e:/P dev/project/Resume_generator/front/angular.json", "owner": "_generated_diagnostic_collection_name_#1", "c ...

How to Retrieve Class Variables in Angular 2 Form Validator Function

I'm in the process of creating a modal-driven form with custom validation requirements. Specifically, I want to ensure that the user's password meets certain criteria (including having an uppercase letter, lowercase letter, and number). Instead o ...

Tips for maintaining license comments in TypeScript 2.5

When creating JavaScript libraries using TypeScript v2.5 and tsc, it is important to include license comments in the built files. However, the removeComments configuration in the tsconfig.json file can remove certain comments, including license comments. ...

Issue encountered during Karma Test run

I am currently facing an issue with my directives set up in the selectprice.directive.js file as shown below: (function() { 'use strict'; angular .module('app.buyouts.selectPrice') .directive('selectPrice', selec ...

React Typescript Issue: Antd Checkbox value not updating correctly

Hey there, I'm having trouble filling the Checkbox value with my state data as it's not accepting it. Here is the Checkbox Code: <Form.Item label="Active"> <Checkbox value={this.state.selectedRecord.active} /> </Form ...

Accessing information from req.files in a TypeScript environment

I am currently using multer for uploading images. How can I retrieve a specific file from req.files? Trying to access it by index or fieldname has been unsuccessful. Even when I log it, I see that it's a normal array, so I suspect the issue may be rel ...

Update the options in a dropdown menu after submitting a modal form

In my scenario, I have a modal form called "AddProductComponent" which is utilized within the "AddServiceRecordsComponent". export class AddProductComponent implements OnInit { id!: string; isAddMode: boolean = false; constructor(private fb: FormBuilder, ...

What steps can you take to determine the specific package version required for Angular development?

After upgrading my asp.net core app from Angular 10.2.4 to version 11, I encountered some issues. Initially, when I ran ng update @angular/core@11 @angular/cli@11, it failed due to complains about devkit. So, I uninstalled devkit and successfully upgraded ...

This Source does not currently provide Content or Map information, but it does support the use of size() in Angular 13

I've been tackling a project in Angular with versions 13 and 16 for Angular and Node, respectively. Whenever I run the command npm run start, it throws a compilation error. Below is the error that gets displayed: Error: Content and Map of this So ...

adjusting state with React hooks

I currently have two buttons labeled create signature and Create delivery in my file PageOne.tsx. When the state is set to InDelivery, both buttons are visible. My goal is to hide the Create delivery button initially. However, when a user clicks on the cr ...

How can I retrieve a value from a jQuery function within an external Angular function?

implement{ let selection; $(".l_item").click(function(){ selection = this.value; }); console.log(this.selection); } This unique jQuery function retrieves the selected value from the l_item array of lists. After obtaining the value, there ...

How can I display a modal with image options and image selection using Ionic 4?

Currently, I am developing an Ionic 4 Angular application and implementing an Ionic modal feature. I would like to include images in the modal, so that when a user clicks on them, they are displayed. ...