What is the best way to simulate a global variable for Unit Testing using Jasmine?

I'm currently facing a challenge while testing a service within my Angular application. Specifically, I am unsure of how to mock a variable that is declared outside of my method.

Here is an excerpt from my service:

export class MyService {
    private token: string

    public myMethod(): Promise<boolean> {
        if(!this.token) // perform certain actions
        else // perform other actions
    }
}

Can someone provide guidance on what steps I might be overlooking?

Answer №1

Expanding on Andrei Gatej's suggestion, we can modify the token to be a getter in order to restrict external classes/contexts from writing to it. This approach will make it easier to mock the token for unit testing purposes.

An implementation could look like this:

export class MyService {
    private _token: string;
    get token(): string {
      return this._token;
    }

    // assign new token values using this._token = ....

    public myMethod(): Promise<boolean> {
        if(!this.token) // perform some action
        else // perform another action
    }
}

In your spec file, assuming it is already set up:

it('should execute the if block', async(done) => {
  spyOnProperty(service, 'token', 'get').and.returnValue(null);
  await service.myMethod();
  await fixture.whenStable();
  // add additional assertions here
});

it('should execute the else block', async(done) => {
  spyOnProperty(service, 'token', 'get').and.returnValue('a sample token');
  await service.myMethod();
  await fixture.whenStable();
  // add more assertions as needed
});

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

Upload a gltf file to a three.js environment using an HTML `<input>` tag

Struggling to incorporate a gltf object into a three.js scene by allowing users to upload it via an HTML input tag. The goal is to choose a specific file from the client's computer, display it on the website, compress it, and then transfer it to a mu ...

Rxjs: accessing the most recent value emitted by an observable

As shown in the demo and indicated by the title const { combineLatest, interval, of } = rxjs; const { first, last, sample, take, withLatestFrom } = rxjs.operators; const numbers = interval(1000); const takeFourNumbers = numbers.pipe(take(4)); takeFourNu ...

Discover the data type of a class attribute's accessor methods in TypeScript

Since TypeScript 4.3 introduced the ability for class properties to have getters and setters of different types since 4.3, I am unsure how to correctly retrieve the types of a property's getter and setter. === Since a class property is treated as a ...

Firebase and React are having trouble communicating because it is unable to access the properties of 'auth'

The issue with the 'Cannot read properties of undefined (reading 'auth')' error in login.js may be related to where it is coming from. Login.js: import { useContext, useState, useEffect } from "react"; import { Link, useNavigate } f ...

How can I tailor the child count in ag grid to fit my needs?

Currently, I am using ag grid with React and have successfully implemented row grouping. However, the parent rows are displaying child row counts in numeric values. Is there a way to customize the style of the row count? Additionally, I am interested in ca ...

The information entered into dynamically generated text fields is not being successfully passed to the request()->validate() array

My form allows users to input their educational background from Elementary school to College. If they wish to include any additional studies, they can click the "Add Other Studies" button, which will then reveal a new set of input fields specifically for o ...

Discover the object in the initial array that is not included in the second array using AngularJS

Imagine having these two sets of objects: first set: [ { id: "123", title: "123", options: [] }, { id: "456", title: "456", options: [ { id: "0123", t ...

Merge the chosen values from the drop-down menu into one string

Any suggestions would be greatly appreciated! I am currently developing an application using ASP.NET web forms that consists of a dropdown list and two list boxes. I want these elements to be cloned whenever a specific button is clicked. However, my issue ...

What is the best way to implement a callback function in JavaScript?

I am looking to update this code to incorporate a callback function. My goal is for the program to first call DynamicLoadScriptForEdit(), followed by calling ExecuteScriptForEdit. Unfortunately, my current implementation is not working as expected. window ...

Simple integration of JSP, JSON, and AJAX

I need help testing a simple login functionality using AJAX. Here's the code snippet: <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Login Test Page</title> <script src="../js/j ...

Issues with properly triggering re-clicking events in AngularJS when using Bootstrap modal

I am currently utilizing Angular JS in combination with Bootstrap modal. Below is the Anchor link I am referring to: <li><a href="#" data-toggle="modal" data-target="#inviteFriendModal" ><span class="frndInvt"></span>Invite Friends ...

Javascript: having trouble with closures and event listeners not getting added

There seems to be a recurring issue that I suspect is related to closures. I have 3 buttons, but when I execute this code, only the last button receives an event listener. This suspicion leads me to believe there might be a problem with closures. Despite ...

How can I showcase an SVG icon received in base64 format using an img tag?

Having trouble displaying SVG/base64 encoded images through the img tag. Here is the issue at hand: Receiving iconData (as a string) from the server. Attempting to display it in my component. No issues with step 1. Encountering a broken image sign with s ...

Maintain the previous droppable positioning after refreshing the page

I am encountering an issue with the .droppable event. I have set up two sections where I can move elements, but every time the page is refreshed, the positioning of the elements reverts to the initial position. How can I maintain the last positioning of th ...

Styling HTML Select Box Options

My goal is to display the user's name and email within an option of a select box: <option>Adda <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caabaeaeab8aafb2aba7baa6">[email protected]</a></option& ...

Overlay jQuery Accordion

I am currently working on an accordion to display old blog posts. However, when using a tab, the section below either moves or jumps around. I want the tab to lay over the rows below it without affecting their position. I have tried various solutions in ...

What is the best way to attach labels to objects in three.js when clicking the mouse?

Is it possible to apply a label to an object in a 3D scene using the three.js library through an onMouseClick event? ...

Show information retrieved from fetch api

Hi there! I've been trying to fetch data from the Avascan API and display it on my HTML page, but so far, I haven't had any luck. I've experimented with using the Fetch API, JSON, and AJAX methods, but none of them seem to work for me. Do yo ...

Elevate your Material UI Avatar with an added level of

Attempting to give a MUI Avatar component some elevation or shadow according to the documentation provided here. <Avatar alt="Cindy Baker" src="/static/images/avatar/3.jpg" /> Enclosing the Avatar within a paper or Card element increases the size o ...

Is it possible to implement Typescript validation for the properties of an object that is returned from a callback function passed to a generic React

TS offers a lot of possibilities, but sometimes it can be challenging to achieve what you want. This is the basic structure of my component: export interface DataTableProps<T> { data: { id: string; view: T; }[]; cellModifications?: ( ...