I have this async function for polling a status url and resolving a promise once the result is no longer pending.
// 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
}
})
}
Its a pretty simple function but its very hard to test because theres a setTimeout inside a promise and theres all this deferring going on. Here's what I have so far, but it doesnt work..
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)
})
})
})
Aucun commentaire:
Enregistrer un commentaire