Javascript 使用Jasmine/Karma测试异步轮询

Javascript 使用Jasmine/Karma测试异步轮询,javascript,testing,jasmine,promise,karma-jasmine,Javascript,Testing,Jasmine,Promise,Karma Jasmine,我有这个异步函数,用于在结果不再挂起时轮询状态url并解析承诺 // asynchronously poll until we get a success or failure function pollVerificationStatus(statusUrl) { return fetch(statusUrl) .then(function(response) { return response.json() }).then(function(response)

我有这个异步函数,用于在结果不再挂起时轮询状态url并解析承诺

// asynchronously poll until we get a success or failure
function pollVerificationStatus(statusUrl) {
  return fetch(statusUrl)
    .then(function(response) {
      return response.json()
    }).then(function(response) {
      if (response.status === "pending") {
        return timeoutPromise(POLL_INTERVAL_MS)
          .then(function() {
            return pollVerificationStatus(statusUrl)
          })
      } else {
        return response
      }
    })
}
这是一个非常简单的函数,但很难测试,因为在承诺中有一个setTimeout,而且所有这些延迟都在进行中。这是我到目前为止得到的,但它不起作用

function jsonResponsePromise(obj) {
  return new Promise(function(resolve) {
    resolve({
      json: function() {
        return new Promise(function(resolve2) {
          resolve2(obj)
        })
      }
    })
  })
}

describe("User Verification Polling", function() {
  beforeAll(function() {
    jasmine.clock().install()
    let count = 0
    spyOn(window, 'fetch').and.callFake(function() {
      count += 1
      return (count % 2 === 0) ? jsonResponsePromise({status:'ok'}) : jsonResponsePromise({status:'pending'})
    })
  })

  afterAll(function() {
    jasmine.clock().uninstall()
  })

  it("pollVerificationStatus()", function() {
    let x = pollVerificationStatus()
    jasmine.clock().tick(POLL_INTERVAL_MS+1)
    return x.then(function(response) {
      expect(window.fetch.calls.count()).toEqual(2)
    })
  })
})

好的,在进一步研究后,我发现了一些提示,但仍然没有解决方案


使用
jasminepromise
,我可以返回异步测试的承诺。使用
jasmine.clock().tick(ms)
,我可以控制
setTimeout
。然而,同时使用它们具有挑战性,因为时钟只需要在调用
setTimemout
时滴答作响,如果必须等待整个轮询间隔,测试就会失败。我被困在同一个问题上,这可能是手动测试可能是最佳选择的情况之一(取决于系统要求)