我的src文件中有此代码,我想为此编写单元测试。我在angular 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);
});
}
最佳答案
安静简单,使用spyOn。
it('Your Service', inject([YourService], (YourService: yourService) => {
spyOn(yourService, 'load').and.returnValue(loadedJSON);