Check if one of divs contains my values in nightwatch

醉酒当歌 提交于 2020-01-02 04:41:08

问题


I have problem with testing my webapp with nightwatch.js. I need to iterate over all div elements on the page to check if there is the one who contains all child elements I added before. For example I have:

<div className = 'myclass'>
    <h2> text1 </h2>
    <h3> second_text1 </h3>
</div>
<div className = 'myclass'>
    <h2> text2 </h2>
    <h3> second_text2 </h3>
</div>

And I want to check if one of divs contains both: 'text2' and 'second_text2'. I tried to add iter function like here: Assert text value of list of webelements using nightwatch.js but I don't know how to check child elements in this div and assert only if none of divs contains my values.


回答1:


Unfortunately, nightwatch does not support promises or general asyncness very well. The blog post here summarises some of the pain points.

Fortunately, it is possible using a combination of browser.elements and browser.perform.

var assert = require('assert');

module.exports = {
    'foobar': function (browser) {
        var isTextFound = false;
        browser
            .url('http://localhost:3000')
            .waitForElementVisible('body', 1000);

        browser.elements('css selector', '.myclass', function (res) {
            res.value.forEach(function (jsonWebElement) {
                var jsonWebElementId = jsonWebElement.ELEMENT;
                browser.elementIdText(jsonWebElementId, function (jsonElement) {
                    var text = jsonElement.value;
                    if (text.indexOf('text1') !== -1 && text.indexOf('second_text') !== -1) {
                        isTextFound = true;
                    }
                });
            });
        });
        browser.perform(function () {
            assert.ok(isTextFound, 'Text found');
        });


        browser.end();
    }
}

Let's go through some of the key points

require('assert')

This is required because nightwatch asserts only operate on DOM elements and hence you can not assert a boolean. This also means that the assertion will not show up on the report, however if it is false, it will throw an error and this will come up.

browser.perform(function(){...})

This puts the assertion onto the command queue so that the assertion will happen afterwards. If this was not there, the evaluation will happen immediately and the assert will fail.

browser.elements('css selector, '.myclass', function(res){...})

This is using the elements api. Please note that the api under the webdriver protocol section do not return web elements directly but return the Selenium representation of web elements (WebElement JSON objects) and hence we have to use special methods such as elementIdText to get information out of them.



来源:https://stackoverflow.com/questions/42597385/check-if-one-of-divs-contains-my-values-in-nightwatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!