量角器 - 查找所有元素和找到的元素的循环长度并单击按钮

Protractor - Find all elements and loop length of found elements and click button

所以我一直在试图弄清楚如何根据找到所有元素的数量来单击按钮 x 次。这意味着如果有 3 个元素被相同的类名找到,那么我们循环 3 次,这应该点击按钮 3 次。

我做过这样的事情:

(新更新,检查底部的编辑post)

通常 element.all(by.className('btn btn-remove btn-outlined')).getText() 是 3,但可以更改为 6 和随机数,所以我的想法是先读取 HTML 中有多少 btn btn-remove btn-outlined,然后点击那么多次发现的元素。因此,如果找到 3 个,则单击按钮 3 次。

然而现在的问题是它正在寻找有多少元素。它也循环了很多次 text.length 但在循环内部它似乎由于某些原因跳过了 it 函数,我无法弄清楚为什么

现在它确实找到了元素的长度,它是 3,它似乎循环了很多次,但它跳过了它的功能(这部分):

      it('Click remove button - ' + i + '/' + text.length, function (done) {

            browser.driver
                .then(() => browser.executeScript("arguments[0].click();", element.all(by.className('btn btn-remove btn-outlined').first().getWebElement())));
                .then(() => done());
        });

        it('Wait for fading button to be gone', function (done) {

            setTimeout(function () {
                done();
            }, 1000);

        });

而且我担心我可能做错了我不知道的事情。

如何找到 DOM 中有多少个给定元素并循环多次 + 单击删除按钮?

编辑代码:

it('Click remove button', function (done) {

    element.all(by.className('btn btn-remove btn-outlined')).getText().then(function (text) {
        console.log(text.length) //returns 3
        for (var i = 0; i < 4; i++) {

            console.log(i); //Does print 0 1 2

            it('Click remove button - ' + i + '/' + text.length, function (done) {

                console.log("Remove button"); //Doesnt print

                browser.driver
                    .then(() => browser.executeScript("arguments[0].click();", element.all(by.className('btn btn-remove btn-outlined').first().getWebElement())));
                    .then(() => done());
            });

            it('Wait for fading button to be gone', function (done) {

                console.log("TIme out"); //Doesnt print

                setTimeout(function () {
                    done();
                }, 1000);

            });
        }
    })
    done();
});

您的 it 内部 for 循环未执行的原因是那些 it 在 运行 时间内动态生成并且未被测试框架 Jasmine、Mocha 尊重。

据我了解,Jasmine 在执行之前需要加载和解析测试脚本文件中的静态 it,在加载和解析阶段之后生成的动态 it 将被忽略。因此你需要删除动态 it.

试试下面的代码

it('Click remove button', function (done) {

    let allBtns = element.all(by.className('btn btn-remove btn-outlined'));

    allBtns.count()
    .then(function (cnt) {

        console.log('Find buttons:', cnt)

        for (let i = 0; i < cnt; i++) { // important to use let but var here.
            console.log('Remove button - ' + i + '/' + cnt);
            browser.executeScript("arguments[0].click();", allBtns.get(i).getWebElement())
            browser.sleep(1000) // sleep 1s
        }
    })
    .then(()=>{
        done();
    })

});