Search code examples
angularangular-test

Spy on same function multiple times with different parameters in Angular Test


Is there any way to call call function two times with different argument.Am using the below code

Have two arguments like below

let dummybody1: any = {
    Product : "New Product",
   
  };
  let dummybody2: any = {
    Product : "New Node",
    
  };

Edit 1

component.ts

addDetailsClick(): void {
let body: any = {
      Product : this.actualselectedprod,
      
    }
    if(this.actualselectedprod == "New Product")
    {
      body.Product = this.newProductName; 
      body.HealthURL = this.healthEndPoint;
    }
    if(this.actualselectedipAddress == "New Node")
    {
      body.Ipaddress = this.newIPAddress;
    }
    let obs = this.cmnService.addEditNodeDetails(body);

    obs.subscribe(data => {
      console.log('success', data)

      this.addNodeMessage = "Successfully Added/Edited Node details";
    },
      error => {
        console.log('oops', error)

        this.addNodeMessage = "Failed to Add/Edit Node details";
      })

    
  }
}

component.spec.ts

    beforeEach(() => {
    
    spyOn(service,'addDetails').and.callFake(function(dummybody1) {
          
          return of('success')     
    
        });
    
    }

it('should be able to click add/new button', () => {
    result = component.addNewNodeButtonClick();
    service.addDetailsClick(dummybody1);
    //service.addEditNodeDetails(dummybody2);
    expect(component.addNodeMessage).toEqual("Successfully Added/Edited Node details");
    });

Am trying to write a test for the method addDetailsClick() with argument as dummybody1.

Tried to add another spy method inside beforeEach for dummybody2

beforeEach(() => {
        
        spyOn(service,'addDetails').and.callFake(function(dummybody1) {
              
              return of('success')     
        
            });
        
       spyOn(service,'addDetails').and.callFake(function(dummybody) {
              
              return of('success')     
        
            });
        
}

getting an error

How can i do similer method having argument `dummybody2.


Solution

  • I believe you're thinking about this from the wrong direction. I see 2 issues:

    1. You seem to be trying to add a mock payload to the spy, as if to say it's only spying for when it receives that parameter.

    If you look at your syntax and go back to your basic JavaScript fundamentals you're not actually passing a payload at all. You're defining a function. What you name the parameter doesn't make any difference.

    spyOn(service,'addDetails').and.callFake(function(dummybody) {
      return of('success')     
    });
    

    This is going to call that fake on anything that comes into addDetails - dummybody in this case is a variable declaration and will become whatever you call service.addDetails(...) with.

    1. From the code provided, your code calls addEditNodeDetails but you're mocking addDetails.