简体   繁体   中英

How to get the text from a shadow dom element

I want to get the text of a shadow dom element to do assertion.

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;
};

I want to do an assertion

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: expected 'Welcome back, user1' to equal undefined

    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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM