【问题标题】:How to get code coverage inside a callback using jest?如何使用 jest 在回调中获取代码覆盖率?
【发布时间】:2018-11-13 02:23:38
【问题描述】:

我在代码覆盖方面遇到问题,无法弄清楚。我正在使用谷歌地理编码 API 来查询在回调函数中返回响应的坐标。 Jest 用于测试。

这是带有回调的可测试调用:

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

有什么我可以尝试或研究的想法吗?唯一的问题是覆盖率,预期的结果很好。

【问题讨论】:

    标签: reactjs google-maps-api-3 callback jestjs google-geocoder


    【解决方案1】:

    代码覆盖率实际上已经在此实现中正常工作。问题是我没有在只有“if”子句的“if”子句中访问“else”语句。

    也可以不监视,而是定义为属性并运行您的测试:

    it('test', () => {
      Object.defineProperty(google, 'maps', {
        value: {
          Geocoder: function () {
            return {
              geocode: jest.fn((adr, callback) => callback(response, 'OK'))
            }
          }
        }
      });
      // expect..
    });
    

    【讨论】:

      猜你喜欢
      • 2014-09-09
      • 2017-01-26
      • 2020-02-25
      • 2021-09-26
      • 2018-06-03
      • 2020-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多