Unit testing Angular components can often uncover errors that would otherwise go unnoticed in production. One common

I need assistance writing a simple test in Angular using Shallow render. In my HTML template, I am utilizing the Async pipe to display an observable. However, I keep encountering the following error:

Error: InvalidPipeArgument: '() => this.referenceDataService.getRoutes() 
    .pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_5__["map"])((routes) => { debugger; return routes || []; }))' for pipe 'AsyncPipe'

Component:

routes$: Observable<RouteModel[]>;
   routes$ = () => this.referenceDataService.getRoutes()
    .pipe(map((routes: RouteModel[]) => {
        debugger;
        return routes || [];
    }));

test:

beforeEach(() => {
    routes = [
        { routeId: 1, prefix:'/test1', route:'/test1' }, 
        { routeId: 2, prefix:'/test2', route:'/test2' }
    ]

    dataServiceMock = {
        getRoutes: () => of(routes)
    };

    shallowComponent = new Shallow(RouteComponent, AppModule)
    .provideMock([
        { provide: ReferenceDataService, useValue: dataServiceMock}
    ])
    .dontMock([FormBuilder]);
});

it('should create',  async () => {
    const { instance } = await shallowComponent.render();
    expect(instance).toBeTruthy();
});

If anyone could provide insight into what the issue might be, I would greatly appreciate it.

Thank you

Answer №1

Have you tested the code by running npm start?

The issue lies in the use of parentheses (). The async pipe is designed to bind to an Observable, not a function that returns an Observable. It is not recommended to call the function in the HTML as it will slow down the application, triggering the function every time change detection occurs.

Consider this revised approach:

// remove the () =>
routes$ = this.referenceDataService.getRoutes()
    .pipe(map((routes: RouteModel[]) => {
        debugger;
        return routes || [];
    }));

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

An unfamiliar data type is provided as a number but is treated as a string that behaves like a number

Here is the code snippet in question: let myVar = unknown; myVar = 5; console.log((myVar as string) + 5); Upon running this code, it surprisingly outputs 10 instead of what I expected to be 55. Can someone help me understand why? ...

Ways to speed up the initial loading time in Angular 7 while utilizing custom font files

Storing the local font file in the assets/fonts folder, I have utilized 3 different types of fonts (lato, raleway, glyphicons-regular). https://i.stack.imgur.com/1jsJq.png Within my index.html under the "head" tag, I have included the following: <lin ...

Creating a unique custom selector with TypeScript that supports both Nodelist and Element types

I am looking to create a custom find selector instead of relying on standard javascript querySelector tags. To achieve this, I have extended the Element type with my own function called addClass(). However, I encountered an issue where querySelectorAll ret ...

Having trouble with Angular 2 Routing and loading components?

I am facing an issue with Angular 2 where it is searching for my component in app/app/aboutus.component, but I cannot pinpoint the source of the problem. Here is my app.component.ts code: import { Component } from '@angular/core'; import { ROUT ...

Combine Two Values within Model for Dropdown Menu

I am currently facing a situation where I have a select box that displays a list of users fetched from the backend. The select box is currently linked to the name property of my ng model. However, each user object in the list also contains an email proper ...

The struggle of implementing useReducer and Context in TypeScript: A type error saga

Currently attempting to implement Auth using useReducer and Context in a React application, but encountering a type error with the following code snippet: <UserDispatchContext.Provider value={dispatch}> The error message reads as follows: Type &apos ...

Guide to exporting (and using) JSDoc annotations in TypeScript NPM packages

Looking to enhance my skills in creating npm packages with TypeScript. I have a small project available at https://www.npmjs.com/package/lynda-copy-course/, and so far, the project structure is successful in: being executable from the command line after ...

Shared validation between two input fields in Angular 2+

I have a unique task at hand. I am working on creating an input field with shared validation. The goal is to ensure that both fields are technically required, but if a user fills in their email address, then both fields become valid. Similarly, if they ent ...

Incorporating timed hover effects in React applications

Take a look at the codesandbox example I'm currently working on implementing a modal that appears after a delay when hovering over a specific div. However, I've encountered some challenges. For instance, if the timeout is set to 1000ms and you h ...

Determine the category of a container based on the enclosed function

The goal is to determine the type of a wrapper based on the wrapped function, meaning to infer the return type from the parameter type. I encountered difficulties trying to achieve this using infer: function wrap<T extends ((...args: any[]) => any) ...

Generics causing mismatch in data types

I decided to create a Discord bot using DiscordJS and TypeScript. To simplify the process of adding components to Discord messages, I developed an abstract class called componentprototype. Here is how it looks (Please note that Generators are subclasses li ...

Developing with Electron JS and TypeScript - Leveraging TS-Node in the primary process

Is there a way to modify the code below in order for the electron main process to utilize Typescript by using ts-node? "scripts": { "shell": "cross-env NODE_ENV=development electron ts-node ./app/main.ts" } ...

How to refresh a specific component or page in Angular without causing the entire page to reload

Is there a way to make the selected file visible without having to reload the entire page? I want to find a cleaner method for displaying the uploaded document. public onFileSelected(event): void { console.log(this.fileId) const file = event.targe ...

I am trying to figure out how to send a One Signal notification from my Ionic app using the One Signal REST API. I have reviewed the documentation, but I am still unable to understand it

Is there a way to send a one signal notification from my ionic app using the one signal API? I have reviewed the documentation but am having trouble with it. While I have set up the service and it is functional, I can only manually send notifications thr ...

Using Conditional Types in Supabase Query results in the TypeScript error, "Type is incompatible with type 'never'."

Query I have encountered a TypeScript issue while working on a Next.js project with Supabase as the backend. To handle responses from Supabase queries, I created some helper types, but I'm stuck on resolving this problem. Helper Types Overview: Belo ...

Improving the Roman Numeral Kata with JavaScript

As a newcomer to the world of coding, I have taken on the challenge of mastering the Roman Numeral Kata using Javascript. I am pleased to report that all the specifications are passing successfully. After refactoring the spec file, I am now focusing on re ...

Creating a custom class to extend the Express.Session interface in TypeScript

I'm currently tackling a Typescript project that involves using npm packages. I am aiming to enhance the Express.Session interface with a new property. Here is an example Class: class Person { name: string; email: string; password: strin ...

Struggling with TypeScript compilation in a Vue.js project? Encounter error code TS2352

Here is my code snippet from window.ts import Vue from 'vue' interface BrowserWindow extends Window { app: Vue } const browserWindow = window as BrowserWindow export default browserWindow Encountering a compilation error Error message: TS2 ...

`Angular 6 and the expiration of Jwt tokens`

I am currently developing an angular application that utilizes jwt for authenticating database calls. However, I encountered a problem where, when the token expires on the server, the app starts displaying blank pages instead of the expected data. This hap ...

Implementing canActivate guard across all routes: A step-by-step guide

I currently have an Angular2 active guard in place to handle redirection to the login page if the user is not logged in: import { Injectable } from "@angular/core"; import { CanActivate , ActivatedRouteSnapshot, RouterStateSnapshot, Router} from ...