Global variable is null in Protractor test when utilized in separate class

I have a TypeScript class where I declared a global variable and used it in a method of the same class. Here is an example:

First TypeScript Class:

export class FirstTestDetails {
    baseProductDetails = {
        baseQty: null,
        basePrice: null,
    };

    public async calculateTotalPrice() {
        await this.txtBaseQty.getAttribute('value').then((baseQty) => {
            this.baseProductDetails.baseQty = baseQty;
            console.log('Base Qty ==> ' + this.baseProductDetails.baseQty);
        });
    }
}

In the above code snippet, the correct value is assigned to the global variable (this.baseProductDetails.baseQty). However, when trying to access the same variable in another class, it returns a 'null' value. Could you please provide guidance?

Second TypeScript Class:

Import {FirstTestDetails} from '../pages/firsttest.page';

const firstTest = new FirstTestDetails();
export class SecondTestDetails {

    async validateQtyFromFirstTest() {
        await this.txtBaseQty.getAttribute('value').then((baseQty) => {
            if (firstTest.baseProductDetails.baseQty === baseQty) {
                console.log('Quantities match between First and Second classes');
            }
        });
    } 
}

However, I am getting a 'null' value for 'firstTest.baseProductDetails.baseQty' instead of the actual value printed in the FirstTestClass function. Is there a way to read the global variable of the first class in the second class? Your assistance is greatly appreciated!

Additionally, my test scenario looks like this:

import { SecondTestClass } from '../pages/xxxxxxx';

const firstTest = new FirstTestClass();
const secondTest = new SecondTestClass();

describe('Qty check', () => {
    describe('Check qty in first test', () => {
        it('As User1 - Check qty in first test', async () => {
            await firstTest.calculateTotalPrice();
            expect(xxxxx).toBeTruthy();
        });

        it('As User1 - Compare qty in second test with first test', async () => {
            await secondTest.validateQtyFromFirstTest();
            expect(xxxxx).toBeTruthy();
        });
    });
});

Answer №1

When you instantiate the firstTest object within the context of the SecondTestClass, there is no need to create a redundant object for FirstTestClass in your specification. You can directly access

secondTest.firstTest.calculateTotalPrice()
within your spec. This is because the firstTest object in your spec file and the one in your SecondTestClass have distinct scopes.

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 query fails to retrieve results for the specified date and the beginning of the month

I have encountered an issue with my query that is supposed to fetch values between the start and end of the month. Interestingly, when a record is entered on the first day of the month, it doesn't get returned in the query result. Only records entered ...

The presence of catchError() within the pipe() function will display an error specifically at the .subscribe stage

I encountered an issue while trying to handle errors for a method in Angular. After adding a catchError check using the .pipe() method, I noticed that the variable roomId was marked with a red squiggly line. The error message read: TS2345: Argument of type ...

A guide on extracting a JSON data with a BigInt type using TypeScript

I am facing an issue with parsing a bigint from a JSON stream. The value I need to parse is 990000000069396215. In my TypeScript code, I have declared this value as id_address: bigint. However, the value gets truncated and returns something like 9900000000 ...

What is the process for extracting TypeScript types from GraphQL query and mutation fields in order to get args?

I am experiencing difficulties with utilizing TypeScript and GraphQL. I am struggling to ensure that everything is properly typed. How can I achieve typed args and parent properties in Root query and mutation fields? For instance: Server: export interfa ...

Initiating preparation during NPM Installation

During the installation of a TypeScript module from Git, I noticed that the package.json file contains a prepare script in its scripts section. Strangely, it seems that the prepare script is not being run when using npm install <git repository#version&g ...

Adding Profile Photos to Authenticated User Accounts in Firebase / Ionic: A Step-By-Step Guide

I have thoroughly gone through the Firebase Docs on "Managing Users" for web along with watching their instructional video on YouTube. Despite following the code they provide, I am encountering an error message that states: "Property 'afAuth' do ...

Evaluating file selection and uploading functionality within Spectron

Currently, I am faced with the challenge of writing a test for an electron GUI that includes a choose file dialog. Unfortunately, I do not have access to the inner workings of the GUI. Here is the code snippet I have written: await app.client.chooseFile( ...

Exploring Angular 8: The Power of Nested Object Interpolation

This is the Angular CLI information I am currently using: Angular CLI: 7.3.9 Node: 12.2.0 OS: win32 x64 Angular: 8.0.2 While working on an Angular 8 project, I am implementing nested FormGroups that represent a specific object structure: const Boilerpla ...

The name 'XXX' is nowhere to be found

I encountered an error stating "Cannot find name 'Calendar Component'" while attempting to add a route to a component from another module in my app.module.ts file. Below is the content of my app.module.ts file: // Importing Modules // import {B ...

Updating parent object data in child: A step-by-step guide

Currently, I am in the process of creating a custom dropdown component. Within this component, I have a config object that is initialized within the ngOnInit() method. This config object combines both default configurations as well as user-provided configu ...

Test fails in Jest - component creation test result is undefined

I am currently working on writing a Jest test to verify the creation of a component in Angular. However, when I execute the test, it returns undefined with the following message: OrderDetailsDeliveryTabComponent › should create expect(received).toBeTru ...

Using the *ngFor directive within an <ng-container> element and wrapping it in an <ng-template> is a great way to dynamically display various data in

I have encountered an issue with my HTML file. The initial content within the ng-container tag is displaying data correctly. However, upon clicking the button to open the details panel, which utilizes the ng-template, only the first data entry from the arr ...

Display a loading indicator as the pdf file is being loaded in the ngx-doc-viewer

Does anyone have additional information on the "googleCheckContentLoaded=true" and "loaded" outputs? I am looking for ways to display loading progress while loading a PDF file. Currently, I am utilizing the ngx-doc-viewer. ...

How can a variable be used to assign a date value to an Angular Material datepicker?

Is there a way to modify the date of an item in an array? I've encountered an issue when attempting to input the selected object's date into the Material datepicker. Strangely, it seems to function properly if you manually type in a date as a str ...

The variable 'minSum' is being referenced before having a value set to it

const arrSort: number[] = arr.sort(); let minSum: number = 0; arrSort.forEach((a, b) => { if(b > 0){ minSum += minSum + a; console.log(b) } }) console.log(minSum); Even though 'minSum' is defined at the top, TypeScript still throws ...

Is React Context malfunctioning due to a syntax error?

Using the function "login" from React context is causing an error for me: const handleLogin = async (data: LoginType) => { try { await login(auth, data.email, data.password); router.push("/Dashboard"); } catch (error: an ...

Transmitting image data (blob) from the frontend to the backend using Next.js and tRPC (T3 stack)

I'm currently facing a challenge in sending a leaflet map image from the backend to the frontend using the leaflet-simple-map-screenshoter library for capturing the image. The library returns a blob, which I need to transmit back to the backend and sa ...

What is the best approach to creating multiple dropdowns in ant-design with unique options for each?

It seems like I may be overlooking a simple solution here. Ant-Design dropdowns utilize an array of ItemProp objects to show the options, but this restricts me to having only one list of options. const choices: MenuProps['items'] = [ { label: ...

Enhancing a UMD module definition with TypeScript 2: A step-by-step guide

Currently, I am in the process of creating TypeScript definition files for two libraries that are meant to be used with the new @types approach. Both libraries adhere to the UMD pattern, allowing them to be consumed either as modules or by referencing them ...

Using Vite with a Chrome Extension Manifest version 3 throws the error "Import statement can only be used inside a module" when attempting to use inpage scripts

I recently developed a browser extension using the foundation of https://github.com/Jonghakseo/chrome-extension-boilerplate-react-vite project. Within the manifest file, I specified the background type as module background: { service_worker: "bac ...