Jasmine's timeout occurs during the testing of rxjs ThrowError

Help Needed: How can I test a rxjs ThrowError without causing Jasmine to time out?


In my project, I am working on testing a service that returns either a completed Observable or an error. The service code is as follows:

import { Observable, of, throwError } from 'rxjs';

export class MyService {
  foo(shouldError: boolean): Observable<any> {
    if (shouldError) {
      return throwError('');
    } else {
      return of();
    }
  }
}

For testing purposes, I have written the following test cases:


describe('MyService', () => {
    let service: MyService;

    beforeEach(() => {
        TestBed.configureTestingModule({});
        service = TestBed.inject(MyService);
    });

    it('handles observable', (done) => {
        const shouldError = false;
        service.foo(shouldError).subscribe(
            (_) => done(),
            (_) => done.fail()
        );
    });

    it('handles error', (done) => {
        const shouldError = true;
        service.foo(shouldError).subscribe(
            (_) => done.fail(),
            (_) => done()
        );
    });
}

However, running these tests causes Jasmine to timeout and display the following error message:

Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)

I am stuck at this point and would appreciate any guidance on how to resolve this issue.

Answer №1

In my previous approach, I discovered that the test subscribers were incorrectly using the next() block, which would not be activated because I return a completed observable.

To rectify this issue, the tests should be structured as shown below:

    it('handles observable', (done) => {
        const shouldError = false;
        service.foo(shouldError).subscribe(
            (_) => done.fail('unexpected next'),
            (_) => done.fail('unexpected error'),
            () => done()
        );
    });

    it('handles error', (done) => {
        const shouldError = true;
        service.foo(shouldError).subscribe(
            (_) => done.fail('unexpected next'),
            (_) => done(),
            () => done.fail('unexpected complete')
        );
    });

The test labeled "handles error" appropriately recognizes that a failed observable is considered complete.

(Furthermore, for improved readability, the tests may benefit from utilizing an observer object:

        service.foo(shouldError).subscribe({
            next: (_) => done.fail('unexpected next'),
            error: (_) => done(),
            complete: () => done.fail('unexpected complete')
        });

)

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 combination of Autodesk Forge Viewer and React with TypeScript provides a powerful platform for developing

I'm brand new to React and Typescript, and I have a very basic question. In the viewer documentation, extensions are defined as classes. Is it possible to transform that class into a typescript function? Does that even make sense? For example, take th ...

Before the file upload process is finished, the progress of tracking Angular files reaches 100%

I am currently developing a service that is responsible for uploading a list of files to a backend server. createFiles(formData: any, userToken: string): Observable<any> { const headers = new HttpHeaders({'Authorization': 'Bearer ...

Spotlight a newly generated element produced by the*ngFor directive within Angular 2

In my application, I have a collection of words that are displayed or hidden using *ngFor based on their 'hidden' property. You can view the example on Plunker. The issue arises when the word list becomes extensive, making it challenging to ide ...

Adding zIndex in typescript and MUI: A step-by-step guide

**Hello, I am facing an issue with my CSS on Vercel. It works fine locally but some styles are not being applied once the project is on Vercel. I was able to fix the background color issue by using !important. However, I am now struggling with applying the ...

JSON store containing Typescript enumeration

Currently I'm utilizing Typescript and Angular 2 in my project, and I am interested in generating enums dynamically based on some JSON data. One specific use case is setting up an enum for a dropdown menu with options fetched from a JSON file. Any su ...

Transforming various date formats into the en-US format of mm/dd/yyyy hh:mm:ss can be accomplished through JavaScript

When encountering a date format in en-GB or European style (mm.dd.yyyy), it should be converted to the en-US format (mm/dd/yyyy). If the date is not already in en-US format, then it needs to be converted accordingly. ...

The input '{ data: InvitedUser[]; "": any; }' does not match the expected type 'Element'

I'm currently facing a typescript dilemma that requires some assistance. In my project, I have a parent component that passes an array of results to a child component for mapping and displaying the information. Parent Component: import { Table } fr ...

Convert JavaScript to TypeScript by combining prototype-based objects with class-based objects

My current challenge involves integrating JavaScript prototype with class-based programming. Here is an example of what I've tried: function Cat(name) { this.name = name; } Cat.prototype.purr = function(){ console.log(`${this.name} purr`) ...

Issues with peer dependencies arise during the installation of npm packages

Seeking help with resolving the following errors: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: x npm ERR! Found: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1 ...

Discover the category of an identifier using the TypeScript compiler API

After analyzing the given input file: function foo (s: string) { console.log(s) } I am looking to automatically determine the data type of s within console.log(s). My goal is to replicate the functionality that VSCode uses to display the type of s when ...

Extract the initial sentence or the opening 50 words from a data object in Typescript/JavaScript

Is there a way to extract only the initial line or first 50 words from the data retrieved by the API and store it in a variable? In the HTML File: <td *ngIf="customizedColumns?.details_of_non_conformity?.value"> <span [ngCl ...

How do you define prop types when passing them in Nextjs?

Welcome to my page import { InferGetServerSidePropsType, GetServerSideProps } from 'next' import ProductList from '../../component/product/ProductList' export interface Item { title: string price: number } const products ...

Adding a visible icon to an Angular Material dropdown: A step-by-step guide

Seeking help on integrating a clear icon to the right side of a dropdown (select component) in Angular Material, only visible when an option is selected by the user. When this "clear" icon is clicked, the value should be deleted and the field res ...

Combine two comma-separated strings in JavaScript to create an array of objects

I have two strings separated by commas that I want to transform into an array of objects. { "id": "1,2,3", "name": "test 1, test 2, test 3" } Is there a way to convert this into the desired object format? { &q ...

Tips for formatting a Date field within an Angular application

After receiving a stringVariable from the backend service, I successfully converted it into a Date field with the following code snippet. date d = new Date(stringVariable ); While this conversion worked fine, the resulting date format is not what I requ ...

Exploring the distinction between invoking a builder function in a chained manner versus invoking it on a variable holding the builder in TypeScript

When utilizing the yargs builder with chained calls as demonstrated in the example below, everything functions correctly. const foo = yargs(stringArray) .string('bar') .describe({ 'bar': 'informative text' ...

Tips for transmitting data from Dart to Typescript Cloud functions, encountering the UNAUTHENTICATED error code

Snippet of Dart code with token passed to sendToDevice: Future<void> _sendNotification() async { CloudFunctions functions = CloudFunctions.instance; HttpsCallable callable = functions.getHttpsCallable(functionName: "sendToDevice"); callable.c ...

Struggling to grasp React class components while working with generics

I'm having trouble understanding how this is supposed to function. I have a parent class with props and an interface for the child class's props. The issue arises with a TypeScript error message: The property 'lineWidth' does not exist ...

Angular log out function to automatically close pop-up windows

Within my application, there is a page where users can open a popup window. When the user clicks on logout, it should close the popup window. To achieve this, I have used a static variable to store the popup window reference in the Global.ts class. public ...

A guide on how to navigate to a customizable element in React Native

After creating a glossary, I needed a way to access the content of a specific letter by clicking on that letter from a list displayed at the top of my page. However, I encountered an issue - while I managed to implement scrolling functionality, I couldn&ap ...