Angular asynchronous unit test ends too soon

I am facing an issue with my Angular unit test using Jasmine-Karma. The test seems to finish prematurely without completing all the steps. Can someone please assist me with this problem?

Output:

LOG: '{"a":"b"}'
LOG: '1'
LOG: 'Finished!'

Error:

null: Unhandled Promise rejection: 'expect' was used when there was no current spec, this could be because an asynchronous test timed out ; Zone: ProxyZone ; Task: Promise.then ; Value:
null: Error: 'expect' was used when there was no current spec, this could be because an asynchronous test timed out

Unit test:

import 'rxjs/add/observable/of';

import { } from 'jasmine';
import { TestBed, inject } from '@angular/core/testing';
import { async } from '@angular/core/testing';
import { Observable } from 'rxjs/Observable';

interface FileResponse {
    data: Blob;
}

class BlobUtil {
    public static asString(blob: Blob) {
        return new Promise<string>((resolve, reject) => {
            var reader = new FileReader();
            reader.onload = (event: any) => resolve(event.target.result);
            try {
                reader.readAsText(blob);
            }
            catch (e) {
                reject(e);
            }
        });
    }
}

class Service {
    public static async SafeCall(executor: Observable<FileResponse>,
        success: (response: string) => void, failure: (error: string) => void) {
        try {
            var response = await executor.toPromise();
            success(await this.Handle(response));
        }
        catch (e) {
            failure(e.message);
        }
    }

    private static async Handle(response: FileResponse) {
        return await BlobUtil.asString(response.data);
    }
}

describe('Tests', () => {

    afterEach(() => {
        console.log("Finished!");
    });

    it("test", async(inject([],
        async () => {
            var request = Observable.of({ data: new Blob(['{"a":"b"}'], { type: 'text/plain' }) });
            await Service.SafeCall(request, response => console.log(response), error => console.log(error));
            expect(true).toBeTruthy();
            console.log("1");
            await Service.SafeCall(request, response => console.log(response), error => console.log(error));
            console.log("2");
            expect(true).toBeTruthy();
            console.log("3");
            await Service.SafeCall(request, response => console.log(response), error => console.log(error));
            console.log("4");
            expect(true).toBeTruthy();
            console.log("5");
        })));
    });

Answer №1

There seems to be a significant issue with Angular's default unit testing framework Jasmine (time to inspect your unit test coverage - this is too critical to have it fail in a release). I've discovered a workaround for now until they address it properly.

To resolve the problem, replace the async function with the code snippet below:

export function async(specFunc) {
  return (done) => {
      specFunc().then(() => {
          done();
      }).catch((error) => {
          done.fail(error);
      });
  };
}

// it("test", async(inject([], ...

p.s. Surprisingly, I couldn't locate any unit tests on Jasmine's GitHub repository... 🤤😲😱😨 Please assure me there are unit tests!

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

Storing Buffer data in Postgres bytea using TypeORM is limited to only 10 bytes

I am encountering an issue while trying to store images in a postgres database, as only 10 bytes of data are being saved. Here is the sequence of events: Initially, I receive a base64 encoded string on my server. I then convert it into a Buffer, assign i ...

Creating a simple unit test for an angular "provider" functionality

I am currently in the process of setting up a basic unit test for my Angular application, specifically an Ionic application. Utilizing a preconfigured solution by the Ionic team with karma/jasmine, the provided sample unit tests passed successfully. Encour ...

What sets apart `const [a, b, c] = array;` from `const {a, b, c} = array;`?

let [x, y, z] = arr; let {x, y, z} = obj; Q: Can you explain the distinction between these two declarations? ...

Issue with Angular2 Karma test runner not refreshing after test execution

Currently going through the Angular2 testing tutorial and facing an issue with Jasmine/Karma. Whenever I run "npm test" and make a change, the test runner attempts to reload but encounters this error: ERROR in C:/dev/unittest1/src/app/banner-inline/ba ...

What is the correct way to extract a value from a keyvalue pair?

When dealing with an object that returns boolean "issues", I specify it as a string. If the value is true, I aim to show a checkmark; if false, I want to display a cross. <ul *ngFor="let filtered of reposFiltered | keyvalue"> <li *ngIf=& ...

What is the reason TypeScript does not display an error when assigning a primitive string to an object String?

From my understanding in TypeScript, string is considered as a primitive type while String is an object. Let's take a look at the code snippet below: let s: string = new String("foo"); // ERROR let S: String = "foo"; // OK It's interesting to ...

Deploying an Angular application with .NetCore on Azure Cloud Platform

I am currently working on a .NetCore Angular project and I have been attempting to publish it on Azure using FTP. After completing the FTP publishing process and accessing the website, I encountered an error: npm ERR! node -v v0.6.20 npm ERR! npm -v 1.1 ...

What are the steps to restrict a user from accessing a specific website?

In my Vue.js project, I've implemented a function that hides a specific menu item for users with insufficient permissions: <a :href="href" @click="navigate" v-if="hideMenuItem()"> // some code </a> hideMe ...

Trying to customize the appearance of vaadin-date-picker's text input

My goal is to make the input text turn red when the date picker is within an element with the class 'has-Error'. Below is an example of what I tried on my index.html page, but unfortunately it didn't work: <style is="custom-style"> ...

Angular 6 Encounter: "ReferenceError: alertify is not defined" - Alertify Error Detected

I recently attempted to integrate alertify.js into my project and followed a tutorial at . However, when I clicked a button in my application, I encountered an error that said ReferenceError: alertify is not defined. In order to add alertifyjs css and js ...

Changing setState in React does not update the current state

My challenge lies in altering the value of a TreeSelect component from the antd (antdesign) UI library. I followed their instructions outlined in their documentation, with the only divergence being the use of Typescript. The issue I encounter is with ch ...

The "number" input type is functioning correctly on Chrome, but on Firefox, it is accepting characters other than numbers

While developing in Angular, I encountered a challenge where I needed to create an input that only accepts numeric characters. Initially, I tried using type="number" which worked perfectly in Google Chrome but surprisingly allowed non-numeric characters ...

An error was encountered at line 52 in the book-list component: TypeError - The 'books' properties are undefined. This project was built using Angular

After attempting several methods, I am struggling to display the books in the desired format. My objective is to showcase products within a specific category, such as: http://localhost:4200/books/category/1. Initially, it worked without specifying a catego ...

Unpacking JSON Objects in Typescript: Working with Private Variables

I have a TypeScript model object called user export class User { constructor( private _name: string, private _email: string ) {} public get name():string { return this._name; } public set name(value:string) { this._name = value; } g ...

The name 'Map' cannot be located. Is it necessary to alter your target library?

After running the command tsc app.ts, an error occurs showing: Error TS2583: 'Map' is not recognized. Should the target library be changed? Consider updating the lib compiler option to es2015 or newer. I want the code to compile without any issu ...

Utilizing Lodash in TypeScript to merge various arrays into one cohesive array while executing computations on each individual element

I am working with a Record<string, number[][]> and attempting to perform calculations on these values. Here is an example input: const input1 = { key1: [ [2002, 10], [2003, 50], ], }; const input2 = { key ...

Encountering a dependency issue when attempting to include an additional component in Angular

Upon attempting to add a new package, I encountered an error message that I am unsure how to resolve. I have updated Angular and the necessary packages, but still cannot figure out how to fix this broken dependency issue. Any guidance on resolving this E ...

Struggling with rotating an image in React

Currently I'm troubleshooting an issue with the rotate button on my React-Avatar Editor. The functionality is not working as intended. For reference, here is a link to the code: https://codesandbox.io/s/example-for-react-avatar-editor-ofoz4 ...

Issue with PrimeNG Carousel width on mobile devices

Currently, I am in the process of developing a system interface with Angular and PrimeNG specifically for mobile devices. The main requirement is to have a carousel to display a set of cards. After evaluating different options, I decided to utilize the ngP ...

Guide to releasing your Angular 6 library to npmjs along with a detailed README.md

I'm currently in the process of developing an Angular 6 library that I intend to share on npmjs. The library, named ng-as-multiselect-dropdown, is versioned on GitHub through the workspace project 'sample'. I used the Angular-CLI command &ap ...