The reduce function does not pass the unit test

Here is a method that is part of an Angular component:

public mapInvoices(invoices: any[]): Record<string, any> {
    return invoices.reduce((map, obj) => {
      map[obj.letterType] = obj;
      return map;
    }, {});
  }

During the unit test for this component, an issue has been detected:

APAUInvoicesDocumentsComponent › should create

    TypeError: Cannot read property 'reduce' of undefined

      37 |
      38 |   public mapInvoices(invoices: any[]): Record<string, any> {
    > 39 |     return invoices.reduce((map, obj) => {
         |                     ^
      40 |       map[obj.letterType] = obj;
      41 |       return map;
      42 |     }, {});

To workaround this problem, one solution is to set a default value for the parameter like this:

public mapInvoices(invoices: any[] = [])

However, the root cause of this issue is still unclear and warrants further investigation.

Answer №1

The reason for this issue is that when mapInvoices is called without a parameter, it defaults to undefined. By setting a default value of an empty array, you are essentially overriding the initial state.

public mapInvoices(invoices?: any[] = []) {}
mapInvoices(); // This call will fail if no default value is set

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

Is there a way to achieve a seamless compilation in TypeScript?

Hopefully this is straightforward! TypeScript Latest version: 1.9.0-dev.20160512 (can be installed using npm install -g typescript@next as suggested by @basarat) Node v5.11.0 Windows 10.0.10586 First file: u1c.ts import * as u1u from "./u1u.ts" let p = ...

The success function is failing to display the Ajax response

Is there a way to correctly display the ajax response of my code? I noticed that when using async=true, only the last value of yy is shown. However, I want to display it for all values from 0 to a. Interestingly, everything works fine when using async=fa ...

The getStaticProps() function in next.js isn't retrieving items as expected

I've been facing issues while trying to load items onto my next.js page: import {getadminInfo} from '../../dataFetch/adminInfo' import {addItem} from '../../dataFetch/catalog' import {useState} from "react" import { getLi ...

Three.js - Exploring the Significance of "THREE" within the THREE.scene Framework

Just starting out in JavaScript and experimenting with animations using three.js library. I'm trying to grasp the meaning behind: const scene = new THREE.Scene(); Why is the "THREE" necessary in THREE.Scene? Could we not simply write const scene = n ...

Optimizing Your Redux Application with ReactJs: Leveraging useEffect to Trigger Actions

One of my components uses Axios to fetch articles, and I'm trying to only retrieve the articles on the initial page load. useEffect( () => { const getArticles = ()=>{ dispatch(getArticlesAction()) } getArticles() }, []) ...

Encountering an error when attempting to reach a JSON endpoint using Javascript and X-Auth-Token

I'm attempting to retrieve data from a JSON endpoint using JavaScript and X-Auth-Token, but I am continuously encountering errors. The data is from a sports API, and despite diligently following all the instructions in the documentation and checking m ...

When a change occurs in the <input/> element within a <div>, the onChange event in React will be triggered

Upon entering text into the input, the onChange function is triggered on this code snippet. How is it possible for the onChange event to occur on a div element? Is there documentation available that explains this behavior? class App extends Component { ...

Passing parameters to functions without using parentheses in JavaScript

One of the functions in my code is named "tryMe", and I want to call it without using parentheses. For example: setTimeout(tryMe,200); How can I pass any necessary parameters in this situation? I am currently using a jQuery plugin that allows me to call ...

Using the on-change event with a textfield can help ensure that the field is cleared if the min-date condition is not met

I recently encountered an issue with an input field that had the type "datetime" and a min-date condition set to today's date. The flow was such that if a valid date was entered, the submit button would be enabled, otherwise it would remain disabled. ...

Using Javascript to add the current date and time into a mysqli query

Currently, I have a database setup with a datetime data type for landing time. I am trying to achieve this using Javascript. The format in the database appears as: 0000-00-00 00:00:00 I have made an attempt with the following code: $('#landing_tim ...

Creating a dynamic parallel route in Next.js by utilizing a static route trigger

In my work with Next.js, I have established the following routes: /@modal/(.)snippets/[id]/page.tsx (serving as a modal) /snippets/[id]/page.tsx (for individual snippet pages) /snippets/new/page.tsx (to create new snippets) An issue arises when I try to ...

Alternative to using the disabled attribute in JavaScript to make a checkbox read-only option

Does anyone know how to make a checkbox readonly so that its value can be submitted, while also disabling it? Using the disable attribute prevents the value from being submitted, and setting it as readonly doesn't seem to work for checkboxes. Your as ...

Directly mapping packages to Typescript source code in the package.json files of a monorepo

How can I properly configure the package.json file in an npm monorepo to ensure that locally referenced packages resolve directly to their .ts files for IDE and build tooling compatibility (such as vscode, tsx, ts-node, vite, jest, tsc, etc.)? I want to a ...

Building a Custom Admin Layout Component in React

I have been trying to create a custom layout for react-admin by following their documentation, but I ran into some issues. For example, the documentation mentioned using a theme in the component, which we didn't have. Additionally, there was a broken ...

Adding a child node before an empty node in Chrome with JavaScript Rangy

When attempting to insert a node before an empty element at the start of another element, a problem was noticed. Here is the initial setup: <p>|<span />Some text</p> By using range.insertNode() on a Rangy range to add some text, Chrome ...

Exploring the iteration of JSON objects within an array using AngularJS

My auto search module has the following JSON structure. I need to iterate through an array of JSON objects and use keys and values as required. I have attempted the code below. However, with the provided JSON object, I am able to retrieve the key but not ...

Trail of crumbs leading to pages displayed in a div container

My website is designed with only one page where all other pages are loaded within a div. I am looking to implement breadcrumbs to keep track of the pages loaded inside the div. However, the solutions I have found online only work for pages loaded in the en ...

"The process of updating a div with MySQL data using Socket.io on Node.js abruptly halts without any error message

Embarking on a new project using socket.io has been quite the learning experience for me as a beginner. Despite extensive research, I managed to reach the desired stage where I have divs dynamically populated with data fetched from MySQL. In my server.js f ...

Tips for transforming Http into HttpClient in Angular 5 (or higher than 4.3)

I have successfully implemented code using Http and now I am looking to upgrade it to use the latest HttpClient. So far, I have taken the following steps: In App.module.ts: imported { HttpClientModule } from "@angular/common/http"; Added HttpClientModul ...

Revealing the Webhook URL to Users

After creating a connector app for Microsoft Teams using the yo teams command with Yeoman Generator, I encountered an issue. Upon examining the code in src\client\msteamsConnector\MsteamsConnectorConfig.tsx, I noticed that the webhook URL w ...