Reputation: 36186
I am trying to use node-xmlhttprequest. So if I do like this
// f.js
(function()
XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest
xhr = new XMLHttpRequest()
xhr.open('GET', "http://url-bla-bla.json", true)
xhr.onreadystatechange = function(){
console.log("xhr "+JSON.stringify(xhr))
}
xhr.send()
)()
and call it node f
(assuming Access-Control-Allow-Origin
is not an issue for http://url-bla-bla.json
link - it works
but If I try it to wrap the same thing into Mocha spec
describe('foo',function(){
it('xhr test',function(){
XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest
xhr = new XMLHttpRequest()
xhr.open('GET', "http://url-bla-bla.json", true)
xhr.onreadystatechange = function(){
console.log("xhr "+JSON.stringify(xhr))
}
xhr.send()
}
}
and run with mocha f
(I don't even have to wrap it in Mocha spec)
it won't work and fail with readyState == 1
Upvotes: 2
Views: 3227
Reputation: 151411
This is an asynchronous operation. In Mocha, you have to use the done
callback to get the test to complete when the operation is complete, like this:
describe('foo',function(){
it('xhr test',function(done){
XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest
xhr = new XMLHttpRequest()
xhr.open('GET', "http://url-bla-bla.json", true)
xhr.onreadystatechange = function(){
console.log("xhr "+JSON.stringify(xhr))
if (xhr.readyState === 4)
done();
}
xhr.send()
});
});
Besides fixing syntax errors, the only other changes are adding the done
argument to the callback to the it
call and calling done()
when onreadystatechanges
executes and the readyState
has reached 4
.
Upvotes: 6