我有一个基于 AJAX 的 javascript 应用程序,我想对其进行接口(interface)测试。例如,我想编写一个测试来加载我的网站(从给定的 URL)并检查是否存在一些 DOM 元素(给定的 ID 和给定的类)。
问题是,当我在浏览器中输入 URL 时,我的应用程序显示了一个 Loading...
标签,并且在下方发送了一个 AJAX 请求。当 AJAX 响应到达时,完成一些处理并显示正确的网页内容(Loading...
标签被隐藏)。到目前为止,我得到了这段代码:
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();
});
});
这是我收到的错误信息:
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
谁能指出我该怎么做才能让 phantomjs/casperjs 等到 AJAX 响应到达并由 JS 引擎处理,以便我可以做出所有断言?
最佳答案
您是否尝试过任何 waitFor 函数。你可以尝试这样的事情:
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();
});
});
然后您可以尝试使用 waitTimeout 选项,以便为页面提供足够的加载时间。这不是一个完美的解决方案,但在这种情况下可以使用。
关于javascript - 使用 phantomjs/casperjs 测试 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17925504/