javascript - How to mock XMLHTTPRequest in typescript for unit test -


i have code in src file , want write unit test this. using karma-webpack in angular 4 application. please suggest

public static load(jsonfile: string): promise<boolean> { console.log('calling loadinstance'); return new promise((resolve: any, reject: any) => {   const xobj = new xmlhttprequest();   xobj.overridemimetype('application/json');   xobj.open('get', jsonfile, true);   xobj.onreadystatechange = () => {     const readyok = 4;     const responseok = 200;     if (xobj.readystate === readyok) {       if (xobj.status === responseok) {         configloader.data = json.parse(xobj.responsetext);         resolve(true);       }       else {         reject(`could not load file '${jsonfile}': ${xobj.status}`);       }     }   };   xobj.send(null); }); 

}

quiet simple use spyon.

it('your service', inject([yourservice], (yourservice: yourservice) => {   spyon(yourservice, 'load').and.returnvalue(loadedjson); 

Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -