使用Casperjs设置单选按钮 [英] Setting radio button with Casperjs
问题描述
我试图用CasperJS设置单选按钮的值没有成功。
I'm trying without success to set the value of a radio button with CasperJS.
有人可以向我解释为什么assertEval在此测试中失败了吗?
Can somebody explain to me why the assertEval is failing on this test?
this.test.assertExist('input[name=main][value=yes]');
casper.thenEvaluate(function(term) {
document.querySelector('input[name=main][value=yes]').setAttribute('checked', true);
});
this.test.assertEval(function() {
return document.querySelector('input[name=main][value=yes]').getAttribute('checked') == "true";
}, 'Main was set to true');
推荐答案
要了解此断言失败的原因,我们需要了解每个对 casper.then
的调用都定义了一个新的导航步骤,而 casper.run
则按顺序执行了每个步骤被定义。因此, casper.then
块中的代码是一个异步回调。
To understand why this assert is failing, we need to understand that each call to casper.then
defines a new navigation step, and casper.run
executes each step in the order that they're defined. So the code within your casper.then
block is an async callback.
如果您对代码进行如下注释:
If you annotate your code like this:
this.test.assertExists('input[name=main][value=yes]');
casper.then(function() {
this.echo('Select the radio button');
this.evaluate(function() {
document.querySelector('input[name=main][value=yes]').setAttribute('checked', true);
}
});
this.echo('Assert that the radio button is selected');
this.test.assertEval(function() {
return document.querySelector('input[name=main][value=yes]').getAttribute('checked') == "true";
}, 'Main was set to true');
您会注意到,在选择单选按钮之前会打印断言单选按钮的声明。因此,这就是您的问题!
You will notice that "Assert that the radio button is selected" gets printed before "Select the radio button". So there's your problem!
如果您不执行任何导航步骤,则可能无需使用然后
。您可以简单地使用 evaluate
而不是 thenEvaluate
。或者,如果您确实需要使用 then
,只需放 assertEval
放入相同的 casper.then
块:
You may not need to use then
if you're not performing any navigation steps. In that case, you can simply use evaluate
instead of thenEvaluate
. Or if you really need to use then
, just put assertEval
into the same casper.then
block:
this.test.assertExists('input[name=main][value=yes]');
casper.then(function() {
this.evaluate(function(term) {
document.querySelector('input[name=main][value=yes]').setAttribute('checked', true);
});
this.test.assertEval(function() {
return document.querySelector('input[name=main][value=yes]').getAttribute('checked') == "true";
}, 'Main was set to true');
});
这篇关于使用Casperjs设置单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!