如何在玩笑代码覆盖率中覆盖 ajax 个调用

How to cover ajax calls in jest code coverage

我在 vue 文件中有以下方法,其中 api 调用如下

getZipcode(city){
         ajax.get(`${CONSTANTS.STANDARDAPIURL}Geographic/ZipCode?cityName=${city}`, {}, (res) => {
                this.zipCode = res.data.zipCode
          })
    }

并且我已经在 ajax.js 文件

中定义了这个 ajax
window.ajax = {
get(url, params, successCallback, errorCallback,coordinates) {
    var that = this;
    let latitude = coordinates == undefined ? "" : coordinates.latitude
    let longitude = coordinates == undefined ? "" : coordinates.longitude
    axios({
      method: "get",
      url: that.formatURL(url),
      params: params,
      responseType: "json",
      headers: { 'X-USER-COORDINATES': `${latitude},${longitude}`}
    })
    .then(function(response) {
        if (
          response.data.Message != null &&
          response.data.Message != "" &&
          response.data.Message ==
            "Authorization has been denied for this request."
        ) {
          window.location.href = "/account/login";
        } else {
          successCallback(response);
        }
      })
      .catch(function(error) {
        that.catchException(error, errorCallback);
      });
} }

我已经将测试用例写成

test("getZipcode method", () => {
    window.ajax = {
        get: jest.fn()
    }
    var wrapper = mount(EmployeeInfo)
    wrapper.vm.getZipcode('city')
    expect(window.ajax.get).toHaveBeenCalled()
})

测试已通过,但 ajax 调用行未包含在代码覆盖范围内,如您在图片中所见 method coverage

有什么方法可以编写测试用例来覆盖 ajax api 调用

谢谢

我通过以下测试用例解决了上述问题

test(`getZipcode method`, () => {
    var res = { data: { zipCode: '72015' } }
    const mockAjax = sinon.stub(window.ajax, 'get').callsArgWith(2, res)
    wrapper.vm.getZipcode('city')
    sinon.assert.calledWith(window.ajax.get, `${CONSTANTS.STANDARDAPIURL}Geographic/ZipCode?cityName=city`)
    mockAjax.restore()
})

还安装了 babel-plugin-istanbul 包和 现在该方法涵盖了预期 method coverage

谢谢