Tuesday, September 8, 2020

Mock XmlHttpRequest /odata request's response in Jasmine Unit test, without using any other module

 WE first need to replace the XmlHttpRequest With a Custom one that we can use for responding to the calls:

Declare a variable in describe, to make it available in all the it nodes

let mockXHR 

In beforeEach add the below code. This replaces the XrmHttpRequestObject definition when triggered, keeping the original definition backup.

mockXHR = {
open: ()=>{console.log('open called from mock')},
send: ()=>{},
setRequestHeader:()=>{},
onreadystatechange:()=>{},
readyState:4,
status:200,
response:JSON.stringify(
              { cci_accountstatus:803230000 }
            ) 
          }; 
window["mockXHR"]=mockXHR;
constoldXMLHttpRequest = window.XMLHttpRequest;
window.XMLHttpRequest =function(){returnmockXHR;};
In it, Call the onReadyStateChange after calling the intended function to be tested.
exampleFunctionCallWhichMakesXHR();
 mockXHR.onreadystatechange();

In afterEach add below, so that the original definition for the XHR is restored after all the tests are executed.
afterEach(() => {     window.XMLHttpRequest = oldXMLHttpRequest;   });

 

No comments:

Post a Comment