我的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);
});
}
答案 0 :(得分:0)
安静简单地使用spyOn。
it('Your Service', inject([YourService], (YourService: yourService) => {
spyOn(yourService, 'load').and.returnValue(loadedJSON);