I have the following method within an Angular component:
public mapInvoices(invoices: any[]): Record<string, any> {
return invoices.reduce((map, obj) => {
map[obj.letterType] = obj;
return map;
}, {});
}
When I run the unit test for this component, I'm getting the following issue:
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 | }, {});
I could bypass this issue by assigning a default value to the parameter like:
public mapInvoices(invoices: any[] = [])
but I would like to understand why this happens.
CodePudding user response:
To answer your question, it is because mapInvoices
is being called with an undefined
parameter. By setting a default value you are actually overriding initial state.
public mapInvoices(invoices?: any[] = []) {}
mapInvoices(); // call bombs without a default value