我在代码覆盖方面遇到麻烦,无法弄清楚。我正在使用Google地理编码API查询在回调函数内返回响应的坐标。 开玩笑用于测试。
这是带有回调的可测试调用:
const geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, (results, status) => {
// want to get coverage in this block
// expected test results are OK and logging shows right results
});
这是测试。由于在测试时默认情况下google.maps不可用,所以我找到了这样的解决方案:
it('test', () => {
const constructorSpy = spyOn(google.maps, 'Geocoder');
const geocoder = createSpyObj('Geocoder', ['geocode']);
constructorSpy.and.returnValue(geocoder);
geocoder.geocode = jest.fn((adr, callback) => callback(response, 'OK'));
// expected results that are all OK
});
createSpyObj https://stackoverflow.com/a/45319913/1756136:
const createSpyObj = (baseName, methodNames): { [key: string]: Mock<any> } => {
let obj: any = {};
for (let i = 0; i < methodNames.length; i++) {
obj[methodNames[i]] = jest.fn();
}
return obj;
};
并且google.maps是在setupTests.js中定义的。未测试时,当react加载google map时google.maps可用
window.google = {
maps: {
Geocoder: {},
GeocoderStatus: {
OK: 'OK'
}
}
};
有什么想法可以尝试或研究吗?问题只在于覆盖范围,预期结果很好。
答案 0 :(得分:0)
代码覆盖范围实际上已经可以在此实现中正常使用。问题是我没有在只有“ if”子句的“ if”子句中访问“ else”语句。
还可以不进行监视,而是将其定义为属性并运行测试:
connection.Open();
command = new OleDbCommand();
command.Connection = connection;
command.CommandText = " update Cards set Count = Count - 1 where Type=" + ct + " ";
command.ExecuteNonQuery();
connection.Close();