问题
I've got an AJAX-based javascript application which I would like to cover with interface tests. For example, I would like to write a test that loads my website (from a given URL) and checks if there are some DOM elements (given ids and given classes) that exist.
The problem is that when I enter the URL in a browser, my application has a Loading...
label displayed and an AJAX request is sent beneath. When AJAX response arrives, some processing is done and the right webpage content is displayed (Loading...
label is hidden). So far I've got this code:
casper.test.begin('Main page test', 2, function suite(test) {
casper.start('http://xxx.yyy.zzz/', function() {
test.assertTitle('My page name', 'page title is set correctly');
});
casper.then(function() {
test.assertExists('#tabsListArea', 'tabs area is found');
});
casper.run(function() {
test.done();
});
});
This is the error message I get:
FAIL tabs area is found
# type: assertExists
# file: mypath/.../casperjs/casper-test.js:11
# code: test.assertExists('#tabsListArea', 'tabs area is found');
# subject: false
# selector: "#tabsListArea"
⚠ looks you did not use begin() which is mandatory since 1.1
Can someone please point me out what can I do to make phantomjs/casperjs wait until the AJAX response arrives and is processed by the JS engine so that I can make all assertions?
回答1:
Have you tried any of the waitFor functions. You could try something like this:
casper.test.begin('Main page test', 2, function suite(test) {
casper.start('http://xxx.yyy.zzz/', function() {
test.assertTitle('My page name', 'page title is set correctly');
});
casper.waitFor(function check() {
return this.evaluate(function() {
return $('loading label').is('hidden');
});
}, function then() { // step to execute when check() is ok
test.assertExists('#tabsListArea', 'tabs area is found');
}, function timeout() { // step to execute if check has failed
this.echo("Timeout: page did not load in time...").exit();
});
casper.run(function() {
test.done();
});
});
You could then play around with the waitTimeout option so you give the page enough time to load. It isn't a perfect solution but it could work in this case.
来源:https://stackoverflow.com/questions/17925504/testing-dom-elements-with-phantomjs-casperjs