-1

I want to know how the "spyOn" function works internally. I read that the 'spyOn' function internally replaces the implementation of the function being spied on. Does it keep the old functionality?

As an example, suppose I wanted to spy on an object that sends data to a server.

describe("A spy", function() {
  var object;
    spyOn(object, 'sendDataToServer');
    object.sendDataToServer('Some Message');
});

In this case, does the message still get sent to the server or does the spy mock it?

1 Answers1

1

The message does not get sent to the server. The way you defined the spy, it will replace the sendDataToServer function whenever it is called in the context of your test case.

You can specify a more elaborate spy, for example when you want to call another function instead:

let mySpy = spyOn(object, 'sendDataToServer').and.callFake((message: string) => {
  console.log('I have been called with ' + message);
});
object.sendDataToServer('Some Message'); // -> will call the function defined above and log the message passed

Or if you want to call the actual function:

let mySpy = spyOn(object, 'sendDataToServer').and.callThrough();
object.sendDataToServer('Some Message'); // -> will call the actual function on object
Fabian Küng
  • 5,925
  • 28
  • 40