I am testing a Backbone View with Jasmine 2.0. The View makes an initial ajax request on load to populate its form field with values. I want my Jasmine test (in the it
function below) to run only after those values are received.
The test currently fails because it seems the ajax request is received after the test runs, even though I am stubbing the ajax request.
How should I be writing this test?
describe('View', function() {
var formFieldValues = [/* blah */];
var view;
beforeEach(function(done) {
jasmine.Ajax.install();
jasmine.Ajax.stubRequest('/form-fields').andReturn({
responseJSON: formFieldValues
});
view = new View({el: $('<main></main>')}); // makes ajax call on initialization
$('body').append(view.el);
});
afterEach(function() {
view.remove();
jasmine.Ajax.uninstall();
});
it('form fields have values', function(done) {
// PROBLEM IS HERE: THE FOLLOWING RUNS BEFORE VIEW'S AJAX CALL FINISHES
expect(view.$('[name="fieldName"]').children().length).toEqual(formFieldValues.length);
});
});