首页 > 解决方案 > testcafe 有没有办法获取特定页面元素的加载时间?

问题描述

假设我导航到一个页面,并且我希望某些页面元素在特定时间段内显示。如何获取加载特定页面元素所需的时间?

我尝试在命令行参数中使用带有选择器超时的可见性检查选项。我还尝试了超时异常。这些都没有按预期工作。

try {
        await loginPage.signInToPortal()
        await loginPage.login( 'xxxx','yyyy')
        await Selector('div').withText('Something').with({ visibilityCheck: true });
    } catch (e) {
        logger.error("Testcase C111111 failed...")
        throw(e)
    }

或者

try {
        await loginPage.signInToPortal()
        await loginPage.login( 'xxxx','yyyy')
        const appLabel = Selector('div').withText('Something').with({ visibilityCheck: true });
        await t.expect(appLabel.innerText).contains('Something', { timeout: 5000 });
    } catch (e) {
        logger.error("Testcase C111111 failed...")
        throw(e)
    }

标签: testingautomated-testsselectorvisibilitytestcafe

解决方案


As far as I understand, you want to check that the element exists and has some inner text after some period of time. If the time passed, but the element does not exist or does not have some text, you want the test to fail.

Your approach is correct in general, but I think you do not need the visibilityCheck option here.

Since I do not know how exactly your project works, I created a sample. Let me show it and explain how timeouts work in TestCafe.

The page:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script>

    setTimeout(() => {
        var div = document.createElement('div');

        document.body.appendChild(div);

        setTimeout(() => {
            div.innerHTML = 'test';
        }, 6000);
    }, 6000);

</script>
</body>
</html>

The test code:

import { Selector } from 'testcafe';

fixture `fixture`
    .page `../pages/index.html`;

const selector = Selector('div', { timeout: 4000 });

test(`Recreate invisible element and click`, async t => {
    await t.expect(selector.innerText).eql('test', 'error message', { timeout: 13000 });
});

Here, I have a div element, which appears only after 6s. During this period, the assertion checks whether the element exists. This code is executed: Selector('div', { timeout: 4000 });. Since 4s is less that 6s, the test fails because it cannot find an element during the timeout.

However, if I change the timeout to 7s, Selector('div', { timeout: 7000}); TestCafe finds the div and starts waiting until the div has correct inner text.

The assertion timeout is 13s now. 13s is greater that 6s (time required for an element to appear) + 6s (time required for an element to have a correct text), so assertion will succeed. However, if I change the assertion timeout from 13s to 11s, it will fail.

See also: Built-In Wait Mechanisms


推荐阅读