Issues encountered when running tests on asynchronous functions in Angular utilizing Jasmine

Currently, I'm facing errors in running unit tests for my Ionic 4 app using Jasmine. It seems like there are issues with the async/await functions as most of my tests are failing with the error message: "Error: Timeout - Async function did not complete within 5000ms." Even after adjusting the timeout interval to a higher value, the error persists.

The code snippet causing this issue is:

beforeEach(async(() => {
  const storage = new Storage({         
    // Define Storage
    name: '__mydb',
    driverOrder: ['indexeddb', 'sqlite', 'websql']
  });  
    
  component = new HomepagePage(storage);

  TestBed.configureTestingModule({
    declarations: [ HomepagePage ],
    imports: [
      IonicModule.forRoot(), 
      RouterTestingModule,
      IonicStorageModule.forRoot()
    ]
  }).compileComponents();

  fixture = TestBed.createComponent(HomepagePage);
  component = fixture.componentInstance;
  fixture.detectChanges();
}));

it('should create', async () => {
  let home = jasmine.createSpyObj('home_spy',['getprice'])
  const result = await home.getprice
  expect(component).toBeTruthy();
});

describe('before logged in', () => {
  let home = jasmine.createSpyObj('home_spy',['getprice'])
    
  it('shows the price', async () => {
    const result = await home.getprice
    expect(home.getprice.length).toEqual(2);
  });
});

Despite the app functioning correctly during normal use, there might be an issue within the code itself. An excerpt from the getprice() function illustrates the logic:

async getprice() {
    var price_eth :number
    var price_btc :number

    try {
        var url_btc = "https://api.binance.com/api/v1/klines?symbol=BTCUSDT&interval=1m";
        var url_eth = "https://api.binance.com/api/v1/klines?symbol=ETHUSDT&interval=1m";
        const btc = await axios.get(url_btc)
        const eth = await axios.get(url_eth)

        if (btc.data.length != 0 && eth.data.length != 0) {
           this.loaded = 'yes'
        } else { 
            this.loaded='no'
        }
        this.time = new Date(btc.data[btc.data.length-1][0]).toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
        price_btc = Math.floor(btc.data[btc.data.length-1][1])
        price_eth = Math.floor(eth.data[eth.data.length-1][1])

       //Global variables set the displayed prices but aren't used elsewhere.
       this.glob_price_btc = price_btc
       this.glob_price_eth = price_eth

       return {
        'price_btc':price_btc,'price_eth':price_eth
       }

    } catch {
        this.loaded = 'no';
        return
    }
}

Answer №1

It appears that there may have been a misunderstanding about the purpose of the beforeEach() function. The correct use of beforeEach() is to set up the testing environment and it is called before each unit test is executed. To clarify, here is an example demonstrating how one could correctly implement this function to set up the timeout duration:

describe("xyz test suite", () => {
    //called before every unittest
    beforeEach(function() {
        //Perform necessary setup tasks
    });
    
    it('displays the price', async () => {
        const result = await getSomething()
        expect(result).toEqual(2);
    });

}, 10000 <- Timeout in milliseconds)

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

Set the CSS attribute value to be equal to twice the value of another CSS attribute value

Currently, I am experimenting with jQuery to create a specific effect that has been presenting some challenges: My goal is to set a css attribute value to be equal to another css attribute value multiplied by 2. To elaborate further, I want the margin-le ...

Issue with AddToAny plugin not functioning properly on FireFox

I’m having issues with AddToAny for social media sharing on my website. It seems like FireFox is blocking it because of tracking prevention measures. Error Message in Console: The resource at “https://static.addtoany.com/menu/page.js” was blocked d ...

Tips for resolving the issue of "Unable to assign property '_DT_CellIndex' to undefined in Jquery Datatable"

<?php if(mysqli_num_rows($result)>0) {?> <table class="table table-striped" id="example" align="center"> <tr> <thead> <th style=&quo ...

Obtain the data from an element within an ng-repeat loop

Here is a snippet of my HTML code: <tr ng-repeat="row in rowCollection"> <td><h6 id="{{$index}}">{{row.inventory_serialno}}</h6></td> </tr> <div class="form-group"> <label for="inventory_serialno">SL No ...

Angular 5's external JavaScript library

After thoroughly researching this subject, I find myself still lacking comprehension. An example may be the key to understanding. As a newcomer to Angular, my goal is to create a mathematical application for mobile using Ionic. Despite investing two weeks ...

What is causing the browser to freeze in this infinite JavaScript loop?

I'm struggling to figure out why the browser is freezing up and getting stuck in the initial for loop within this function. Even when I try using arguments.length, it doesn't seem to log anything in the console. Take a look at the click function ...

Vue.js view fails to refresh upon receiving an event through eventbus

Just diving into Vue.js 2 and working on my very first (vue) web application. The setup includes two components - a header component and a login component. Once the login process is successful, a "loggedIn" flag gets toggled within an authentication servic ...

Building a versatile and interactive table using AngularJS with data sourced from a

I am currently working on creating a dynamic table using Angular JS to display data received from a Spring Rest Service. Here is the code snippet I have been working with: // JavaScript Document var app = angular.module("SDLC", []); app.config([&apos ...

What are the best practices for securely using JSON.stringify in JavaScript?

When I use JSON.stringify on a string that includes <script> tags, the script tags somehow escape and show up in the body of my document, causing unexpected results with the "injected" data. I'm puzzled by how they manage to escape, considering ...

Implementing a NestJs application on a microcomputer like a Raspberry Pi or equivalent device

I'm facing a challenge in trying to find a solution for what seems like a simple task. I am aware that using the Nest CLI, I can utilize the command "nest build" to generate a dist folder containing the production files of my project. However, when I ...

Which video format is best to enable transparent video on web applications for both desktop and mobile, ensuring compatibility with all browsers on these platforms?

My NextJS web application utilizes a transparent video, currently available in MOV and WEBP formats. Interestingly, WEBP works perfectly on Chrome (Desktop) while MOV is optimized for Safari (Desktop). However, I encounter difficulties when viewing the v ...

Any idea how to resolve this typescript typing issue: "The argument, either a string or number, cannot be assigned to the parameter of type 'SetStateAction<string>'"?

Just recently delving into TypeScript, I've encountered a persistent typing problem that has proven challenging to resolve despite numerous attempts. The error message causing me trouble reads as follows: Argument of type 'string | number' ...

Creating a project that utilizes Bing Translate and the Node.js programming language

As I work on developing a web application that enables users to translate text using the Bing translator API, I am facing an issue. I attempted to execute a translator.js file via a script tag, but encountered a roadblock since Node.js code cannot be run t ...

Unable to establish a breakpoint in a source-mapped file (illustrated using jQuery)

Having trouble setting a breakpoint on a minified JavaScript source file that is mapped to real sources using a source map file. An example of this problem can be seen on the website jquery.com. On this particular site, the imported script is jquery.min. ...

Display information using an ASP.Net barcode scanner

Currently, I am developing a WCF service application that involves receiving characters from a barcode reader and displaying the data on the UI for the user. My issue arises when inputting data using the keyboard into a textbox; everything functions corr ...

The array value remains unchanged when included in the response

My goal is to send back the "projets" array within an expressJs route after fetching images for each item. However, when I return the response with the updated array, the newly added fields don't seem to be included. Note: When I log the added item, ...

Execute a Python script using an Ajax jQuery call

Recently, I encountered an issue when attempting to execute a python file via jQuery. To address this problem, I conducted research online and came across a specific code snippet designed to call and run a python script. Below is the AJAX code utilized fo ...

Pass data that has been asynchronously resolved from the parent component to the child component using props in Vue

Main component: <template> <div> <Nav :data="data" /> </div> </template> <script lang="ts"> // ... imports removed for clarity @Component({ components: { Nav: () => import('@/components/Nav.vue&ap ...

Exploring Composite Types with TypeScript's `infer` Keyword

After implementing redux in my project, I found myself including the following code snippet in my store: type CombinedParamTypes<T extends { [key: string]: (state: any, action: any) => any; }> = T extends { [key: string]: (state: infer R, ...

Manipulating the content within an iframe through javascript executed from the parent document

I have a basic website located in A.html <body> <p class="text">Some text</p> </body> There is also another site that displays A within an iframe on B.html <body> <iframe id="frame" src="B.html" onload="onLoadHan ...