我正在尝试测试todo应用程序是否具有正确数量的元素.
文档似乎几乎只涉及单个元素,因此我不得不使用Selenium Protocol函数.这是测试匹配选择器计数的正确方法(在这种情况下,检查2个li元素)?
client.elements('css selector','#todo-list li', function (result) {
client.assert.equal(result.value.length, 2);
});
Run Code Online (Sandbox Code Playgroud)
这适用于我的测试,但我不确定是否有使用回调的问题.也不确定为什么Nightwatch没有任何处理多个元素的辅助函数.
Chr*_*s K 13
我在VueJS模板中找到了以下非常优雅的解决方案.它显示了如何在Nightwatch中添加自定义断言,该断言计算选择器返回的元素数.有关如何在Nightwatch中编写自定义断言的详细信息,请参阅http://nightwatchjs.org/guide#writing-custom-assertions.
安装后,使用方法非常简单:
browser.assert.elementCount('#todo-list li', 2)
Run Code Online (Sandbox Code Playgroud)
插件:
// A custom Nightwatch assertion.
// the name of the method is the filename.
// can be used in tests like this:
//
// browser.assert.elementCount(selector, count)
//
// for how to write custom assertions see
// http://nightwatchjs.org/guide#writing-custom-assertions
exports.assertion = function (selector, count) {
this.message = 'Testing if element <' + selector + '> has count: ' + count;
this.expected = count;
this.pass = function (val) {
return val === this.expected;
}
this.value = function (res) {
return res.value;
}
this.command = function (cb) {
var self = this;
return this.api.execute(function (selector) {
return document.querySelectorAll(selector).length;
}, [selector], function (res) {
cb.call(self, res);
});
}
}
Run Code Online (Sandbox Code Playgroud)
此代码在2016年由yyx990803添加到vuejs-templates中.因此完全归功于yyx990803.
只是为了让你放心,我在尝试抓住所有匹配元素时做了类似的事情,例如:
browser.elements("xpath","//ul[@name='timesList']/h6", function(result){
els = result.value;
var i = 0;
els.forEach(function(el, j, elz){
browser.elementIdText(el.ELEMENT, function(text) {
dates[i] = text.value;
i++;
});
});
});
Run Code Online (Sandbox Code Playgroud)
或者,如果您想确定n存在多少元素,可以使用:nth-of-type/ :nth-childselectors和nightwatch的组合expect.
例如,如果你想测试是否#foo有九个直接孩子:
function(browser) {
browser
.url('http://example.com')
.expect.element('#foo > *:nth-child(9)').to.be.present;
browser.end();
}
Run Code Online (Sandbox Code Playgroud)
或者如果#bar有三个直接article孩子:
function(browser) {
browser
.url('http://example.com')
.expect.element('#bar > article:nth-of-type(3)').to.be.present;
browser.end();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17283 次 |
| 最近记录: |