Search code examples
ajaxtypescriptjasminespy

Typescript syntax - How to spy on an Ajax request?


I am trying to write a unit test where I want to verify that a ajax call has been made. The code is simple :

it('test spycall',()=>{
spyOn($,"ajax");
//my method call which in turns use     ajax
MyFunc();
expect($.ajax.calls.mostRecent().args[0]["url"].toEqual("myurl");
});

The error that I get :

Property 'calls' doesn't exist on type '{settings:jqueryAjaxSettings):jQueryXHR;(url:string, settings?:JQueryAjaxSettings}


Solution

  • $.ajax.calls, among others, is part of the Jasmine testing framework, not JQuery itself (As you know, Jasmine (or rather, Jasmine-Jquery, the plugin you're using) is adding certain debugging functions to JQuery's prototype in order to, well, be able to test ajax calls).

    The bad part is that your .d.ts typescript definition file, the file that acts as an interface between typescript and pure JS libraries isn't aware of Jasmine's functions.

    There are several ways you could approach fixing this, like

    • looking if someone has adjusted the JQuery .d.ts file for Jasmine's functions or
    • creating the new .d.ts file yourself by modifying the original one or, (what I would be doing)
    • overwriting the typescript definition by declaring $.ajax as any, or not including the typescript definition at all in your testing codebase and declaring $ as any.