Reputation: 255
I'm trying to test a module (uses browserify to bundle) that does a XMLHttpRequest. The module looks like:
module.exports = function(year, cb) {
var xhr = new XMLHttpRequest();
xhr.open('GET', encodeURI('data/' + year + '.json'));
xhr.onload = function() {
if (xhr.status === 200) {
var counties = JSON.parse(xhr.responseText);
cb(counties);
} else {
cb(xhr.status);
}
};
xhr.send();
};
My Jasmine test looks like:
var counties = require('myModule');
describe('did ajax call respond', function() {
var countyList;
beforeEach(function(done) {
counties(2015, function(data) {
countyList = data;
});
done();
});
it('should return', function(done) {
console.log(countyList);
expect(countyList).not.toEqual({});
expect(countyList).not.toBeUndefined();
done();
});
});
I've seen this question - Why is Jasmine not executing it() on this async test? - which seems to be the exact same thing but it's still not working.
I'm getting undefined
for countyList
. My jasmine output is:
did ajax call respond
X should return
Expected undefined not to be undefined. (1)
Thanks for any help!
Upvotes: 1
Views: 442
Reputation: 11733
Your done()
is in the wrong place. It must be inside the callback function passed to counties
:
beforeEach(function(done) {
counties(2015, function(data) {
countyList = data;
done();
});
});
This will ensure that the it
methods will only be called after done
is executed, so, after data
has returned, and you already have your countyList
populated.
Upvotes: 1