如何在typescript中模拟XMLHTTPRequest以进行单元测试

时间:2017-09-11 07:17:54

标签: javascript angular unit-testing webpack jasmine

我的src文件中有这个代码,我想为此编写单元测试。我在角度4应用程序中使用karma-webpack。请建议

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);
});

}

1 个答案:

答案 0 :(得分:0)

安静简单地使用spyOn。

it('Your Service', inject([YourService], (YourService: yourService) => {
  spyOn(yourService, 'load').and.returnValue(loadedJSON);