Reputation: 21
I am using Jasmine jQuery to test a custom javascript module's AJAX request and ultimately it's post-process manipulation of the DOM, but my Jasmine test is not locating the newly manipulated elements.
The Jasmine test is as follows...
describe("#init", function() {
it("should return a JSON object from the server", function() {
loadFixtures("top_content_container.html");
// This method will add 'div.search_result' to the 'div.top_content' container
SC.init();
expect($('div.top_content')).toContain('div.top_content_container');
expect($('div.top_content')).toContain('div.search_results');
// THIS TEST SHOULD PASS, BUT DOES NOT DETECT THE DOM UPDATES AND DOES NOT
expect($('div.top_content div.search_result').length == 10).toBeTruthy();
});
});
Within the SC.init()
method it adds elements to the DOM then runs an AJAX request, which returns data and injects it into the DOM. These newly created elements match "div.search_result".
I have confirmed that all the AJAX requests are running properly and the SC library is properly injecting all the elements into the DOM; from a functionality perspective the library is working. The problem is how to get the Jasmine test to see the updates to the DOM. Again, I do not need help debugging the SC codebase; I need help debugging the test itself.
Do you see anything out of whack?
Upvotes: 0
Views: 626
Reputation: 2779
Libraries like https://github.com/velesin/jasmine-jquery will give you more power. However, a crude solution is also possible using runs/waitsFor for asynchronous queries.
it("should load asynchronously", function() {
runs(function() {
$el = $('<div id="jasmine-insert">').appendTo('body');
$el.load('path/file.html');
});
waitsFor(
function() { return $el.html().length > 0; }, // tested at intervals
"html couldn't be loaded", // message on error
500); // wait time out
runs(function() {
expect($('div.top_content').find('div.top_content_container').toEqual(1));
});
});
Upvotes: 0
Reputation: 18567
AJAX is asynchronous so your Jasmine spec is probably reaching the assertion about search results before the AJAX request has received a response. You may want to do a jasmine.Ajax.useMock()
before calling SC.init()
and then pass it a successful response. You'll need Jasmine-Ajax for this.
Upvotes: 1