Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

reduce method fails unit test

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

but I would like to understand why this happens.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading