Spying on callback functions

Let's see how we can use a spy to test whether a callback function was invoked correctly. Consider the following TypeScript code:

class CallbackClass { 
    doCallback(id: number, callback: (result: string) => void ) { 
        let callbackValue = "id:" + id.toString(); 
        callback(callbackValue); 
    } 
} 
 
class DoCallback { 
    logValue(value: string) { 
        console.log(value); 
    } 
} 

Firstly, we define a class named CallbackClass that has a single function, doCallback. This doCallback function takes an id argument, of type number, and also a callback function. The callback function must take a string as an argument and return void.

The second class that we have defined, named DoCallBack, has a single function, named logValue. This function signature matches the callback function signature required on the doCallback function we defined earlier. Using Jasmine spies, we are now able to test the logic of the doCallback function of the CallbackClass.

This function must create a string based on the id argument that was passed in and then invoke the callback function. Our tests must therefore accomplish two things. Firstly, we need to ensure that the string generated within the doCallback function is formatted correctly, and secondly, we need to ensure that our callback function was indeed invoked with the correct parameters. Our Jasmine test for this functionality is as follows:

describe("using callback spies", () => { 
    it("should execute callback with the correct string value",  
        () => { 
        let doCallback = new DoCallBack(); 
        let classUnderTest = new CallbackClass(); 
 
        let callbackSpy = spyOn(doCallback, 'logValue'); 
        classUnderTest.doCallBack(1, doCallback.logValue); 
 
        expect(callbackSpy).toHaveBeenCalled(); 
        expect(callbackSpy).toHaveBeenCalledWith("id:1"); 
 
    }); 
}); 

This test code firstly creates an instance of the CallbackClass class, and also an instance of the DoCallback class. We then create a spy on the logValue function of the DoCallback class. Remember that the logValue function is passed into the doCallBack function as the callback function parameter, and will be invoked with the formatted string.

Our expect statements on the last two lines verify that this callback chain has indeed been executed correctly. The first expect statement simply checks that the logValue function was invoked, and the second expect statement checks that it was called with the correct parameters. So, we have tested the internal implementation of the CallbackClass and the doCallback function, checking that it formats the string properly, and also checking that the callback function itself was invoked.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.156.46