如何从阴影dom元素获取文本

时间:2018-08-28 09:41:14

标签: javascript assertions shadow-dom cucumberjs

我想获取shadow dom元素的文本进行断言。

function shadowSelectorFn(el, selector) {
    if (el && el.shadowRoot) {
        return el.shadowRoot.querySelector(selector)
    }
    return;
};

async function queryDeep(selector) {
    let selectors = selector;
    if (selector && !Array.isArray(selector)) {
        selectors = selector.split(">>>");
    }
    if (!selectors || selectors.length === 0) {
        return;
    }

    const [firstSelector, ...restSelectors] = selectors;
    let parentElement = await page.$(firstSelector);
    for (const selector of restSelectors) {
        parentElement = await page.evaluateHandle(shadowSelectorFn, parentElement, selector);
    }
    if (!parentElement || !parentElement["_remoteObject"] || parentElement["_remoteObject"].type == "undefined") {
        return null;
    }
    return parentElement;
};

我要断言

Then('Username {string} should be displayed in top right corner', async function (string) {
    const text = await queryDeep(["abc-prq", "[class=mess]"]);
    const welcomeUser = await text.innerHTML;
    expect(string).to.be.equal(welcomeUser);
});
  

AssertionError:预期的“欢迎回来,user1”等于未定义

1 个答案:

答案 0 :(得分:0)

    async function getElementProperty(elementHandle, property) {
    let page = global.page;
    let propHandle = await page.evaluateHandle(
        (element, property) => element[property],
        elementHandle, property
    );
    return propHandle.jsonValue();
}

    Then('Username {string} should be displayed in top right corner', async function (string) {
    const text = await queryDeep(["abc-prq", "[class=mess]"]);
    const welcomeUser = await getElementProperty(text, "innerText");
    expect(string).to.be.equal(welcomeUser);
});