我有一个简单的表单,我想填写并提交它,以测试它是否按预期工作。
以下是本应有效但实际上无效的代码。我已经尝试过以多种方式提交表单,但都没有触发页面重新加载。
casper.test.begin('Showcase signup works', 2, function suite(test){
casper.start('https://my.vidzor.com/accounts/signup/', function(){
test.assertExists('form', 'Signup form found');
this.fillSelectors('form', {
'input[name="name"]': 'Test User',
'input[name="email"]': 'test@example.com',
'input[name="password"]': 'example',
'input[name="password_confirm"]': 'example'
}, true);
this.click('button[type="submit"]');
this.evaluate(function submitForm(){
$('form').submit();
});
this.wait(10000);
this.captureSelector('signup-form.png','input#id_name');
var form_values = this.getFormValues('form');
console.log(JSON.stringify(form_values));
test.assertEqual(form_values.stage, "2");
});
casper.run(function() {
test.done();
});
});
我注意到了很多奇怪的事情。
form_values
不包含名称和电子邮件字段,即使它们已填充captureSelector
对整个页面进行了截图;实际上,当我只将其称为"表单"时,它就捕获了页面的不同部分- 页面似乎从未提交过(10秒的等待时间肯定超过了加载下一个页面所需的时间,并且屏幕截图中没有显示错误)
我在这里想念什么?
您必须牢记CasperJS的异步特性。所有的wait*
和then*
函数都是异步步进函数,用于调度一些行为。如果在调用wait
之后调用像captureSelector
这样的同步函数,那么在这两者之间没有等待。它们必须在wait
:的then
回调内进行调度
this.wait(10000, function then(){
this.captureSelector('signup-form.png','input#id_name');
var form_values = this.getFormValues('form');
console.log(JSON.stringify(form_values));
test.assertEqual(form_values.stage, "2");
});
如果表单提交处理程序不是异步的,那么以下操作应该在没有显式等待的情况下工作:
casper.start('https://my.vidzor.com/accounts/signup/', function(){
this.fillSelectors('form', {
'input[name="name"]': 'Test User',
'input[name="email"]': 'test@example.com',
'input[name="password"]': 'example',
'input[name="password_confirm"]': 'example'
}, true);
});
casper.then(function(){
this.captureSelector('signup-form.png','input#id_name');
var form_values = this.getFormValues('form');
console.log(JSON.stringify(form_values));
test.assertEqual(form_values.stage, "2");
});