Ways to check the functionality of the secondary tier in the api.send method

Currently, I am testing a function that involves returning a promise and subsequently calling the same function again at a second level. However, I am facing difficulties in accessing this second level of call.

Below is the function code:

itemToForm = () => {
        this.api.send(this.component, 'get', { lang: 'ES', filter: { id: this.item['id'] } }).then(resEsp => {
            this.item = resEsp['data'][0];
            this.api.send(this.component, 'get', { lang: 'EN', filter: { id: this.item['id'] } }).then(res => {
                let itemEng = res['data'][0];
                let fields = this.formDef
                    .map(register => register
                        .filter(field => field['register_table'].indexOf('traduction') !== -1)
                        .map(field => field['field_name'])
                    ).filter(register => register.length);

                fields = fields.length ? fields[0] : [];
                if (itemEng)
                    this.item = Object.keys(itemEng)
                        .reduce((obj, key) => {

                            obj[key] = this.item[key];
                            if (fields.indexOf(key) !== -1) {
                                obj[key + '_eng'] = itemEng[key];
                            }

                            return obj
                        }, {});
                if (this.item) {
                    this.setForm();
                }
            });
        });
    }

Although I have successfully tested the first level of the function, I am struggling with setting up the spyOn mock for the second level call.

Here is my test scenario:

describe('itemToForm()', () => {
        it('should call api.send with resEsp', () => {
            let item = { id: 1, name: 'test' };
            component.component = 'Events';
            let resEsp = {
              data: [
                { id: 1, name: 'test1' },
                { id: 2, name: 'test2' },
                { id: 3, name: 'test3' }
              ]
            };
            component.item = item;

            //let spy1 = spyOn(api, 'send').and.returnValue(Promise.resolve(resEsp));
            let spy1 = spyOn(api, 'send').and.returnValue(Promise.resolve(resEsp));
            component.itemToForm();

            expect(spy1).toHaveBeenCalled();
            expect(spy1).toHaveBeenCalledTimes(1);
            expect(spy1).toHaveBeenCalledWith('Events', 'get', { lang: 'ES', filter: { id: 1 } });
        });
        it('should call api.send with res Eng', () => {
          let itemEng = { id: 1, name: 'test', lang: 'EN' };
          component.component = 'Events';
          let resEsp = {data: [{ id: 1, name: 'test1' }, { id: 2, name: 'test2' }, { id: 3, name: 'test3' }]};
          let res = {data: [{ id: 1, name: 'test1' }, { id: 2, name: 'test2' }, { id: 3, name: 'test3' }]};
          component.item = itemEng;

          //let spy1 = spyOn(api, 'send').and.returnValue(Promise.resolve(resEsp));
          let spy1 = spyOn(api, 'send').and.returnValue(Promise.resolve(resEsp)).and.returnValue(Promise.resolve(res));
          component.itemToForm();

          expect(spy1).toHaveBeenCalled();
      });
    });

Answer №1

Instead of using returnValues, consider utilizing returnValues to efficiently return multiple values in a sequence.

let spy1 = spyOn(api, 'send').and.returnValues(Promise.resolve(resEsp), Promise.resolve(res));

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

Having trouble with the download link for files in Angular?

I am facing an issue with a PDF file in my Angular website application. The file is 33 KB and located at src/app/components/landing-page/res/File.pdf In the landing-page.component.html within the landing-page folder, I added the following line to enable ...

`Angular2 Reactively-shaped Form Elements with BehaviorSubject`

As a newcomer to Angular, I am struggling with updating reactive forms after making asynchronous calls. My specific challenge involves having a reactive form linked to an object model. Whenever there is a change in the form, it triggers an HTTP request th ...

Is it possible to incorporate regular React JSX with Material UI, or is it necessary to utilize TypeScript in this scenario?

I'm curious, does Material UI specifically require TypeScript or can we use React JSX code instead? I've been searching for an answer to this question without any luck, so I figured I'd ask here. ...

Printing feature not functioning properly on Internet Explorer version 11

Currently, I am facing an issue with printing a document using a blob URL and iFrame. Everything works perfectly in Chrome, but unfortunately, it's not functioning properly in IE browser. I need guidance on how to successfully print a blob URL that i ...

What is the key to ensuring the content in your canvas adapts to different screen sizes

Greetings! I wanted to extract the values from this specific meta tag: <meta name="viewport" property="viewport" content="width-device-width, initial-scale=1"> To retrieve content from a meta tag using JavaScript, I used the following code snippet: ...

Is it necessary to create a unit test for a basic operation involving RxJS?

Imagine a straightforward class that triggers a new event to an RxJS subject whenever the window is resized. Disregard any perceived complexities, as the main point is that this class generates an event. export class ResizeService { priv ...

Problem with MongoDB - increasing number of connections

I have encountered an issue with my current approach to connecting to MongoDB. The method I am using is outlined below: import { Db, MongoClient } from "mongodb"; let cachedConnection: { client: MongoClient; db: Db } | null = null; export asyn ...

Refresh an array prior to subscribing in Angular 2

When attempting to apply multiple filters in a quick session, I am encountering an issue where the previous data persists in the array alongside the new data. How can I effectively remove the previous data? component.ts ngOnInit() { this.vehicleAttribu ...

What causes TypeScript to interpret an API call as a module and impact CSS? Encountering a Next.js compilation error

My website development process hit a roadblock when I tried integrating Material Tailwind into my project alongside Next.js, Typescript, and Tailwind CSS. The compilation error that popped up seemed unrelated to the changes, leaving me baffled as to what c ...

Struggling to convert a JSON response into an object model using TypeScript in Angular?

I'm encountering a problem when trying to convert a JSON response into an object. All the properties of my object are being treated as strings, is that normal? Below is my AJAX request: public fetchSingle = (keys: any[]): Observable<Medal> =&g ...

Having trouble linking tables to Node.js with TypeScriptyntax?

I am facing an issue with mapping multiple entities using sequelize. I keep encountering the error message " Error: Profesor.hasOne called with something that's not a subclass of Sequelize.Model". How can I resolve this issue? Below is the code for t ...

Encountered an issue when attempting to access a user's full details page in Angular 14

An error occurred in main.ts at line 6: TypeError - Cannot read properties of undefined (reading 'id'). The issue is located in the ContactUserDetailsComponent_Template in contact-user-details.component.html at line 17. This error is being hand ...

What is the method for determining if an ngModel input field has been modified?

I'm currently working with this HTML template: <input type="text" ngModel #myValue="ngModel" name="{{ fieldName }}" id="{{ fieldName }}" value="{{ myVal }}" class="form-control" (change)="checkDirty(myValue)"> How can I determine ...

The inner panel height does not extend to 100% when there is overflow

When pressing the submit button on a panel containing components, an overlay appears but does not cover the entire parent panel if scrolled to the bottom. Additionally, I want the spinner to always be centered, whether scrolling or not. I've tried usi ...

Footer missing from Tanstack React table

Library Version: "@tanstack/react-table": "^8.2.6", I have been attempting to include footers in my table without success. Despite setting static footer text with a fixed value, I am unable to render any dynamic values similar to how h ...

Angular - Enhancing the page with valuable information

Recently, I've been developing an Angular application that is designed to function as a digital magazine. This app will feature articles, news, reviews, and more. Along with this functionality, I am looking to include an admin panel where I can easily ...

The function screen.getByText is not available in this context

My experience with jest and react-testing-library has been smooth for the most part, but I encountered some challenges when transitioning to the screen > getByText/etc testing method. Test describe('test the dashboard when loaded', () => { ...

ReactJS: A single digit input may result in the display of numerous '0's

My goal is to have a small box that only allows one digit, but it seems to work fine until I try to input multiple '0's. Then the box displays multiple 0000 persistently. https://i.sstatic.net/Ouot4.png https://i.sstatic.net/MMKjm.png H ...

What sets apart exporting a component from importing its module in another module?

When working with Angular, consider having both module A and module B. If I intend to utilize "A-component" within components of module B, what is the distinction between importing module A in Module B compared to including the "A-component" in the exports ...

Alert: User is currently engaging in typing activity, utilizing a streamlined RXJS approach

In my current project, I am in the process of adding a feature that shows when a user is typing in a multi-user chat room. Despite my limited understanding of RXJS, I managed to come up with the code snippet below which satisfies the basic requirements for ...