首页 > 解决方案 > 如何在 Test Cafe 中使用 Javascript 将表作为数组返回

问题描述

我正在尝试验证整个表格元素并希望将表格作为数组返回,然后想要访问每个元素..请帮助。

标签: javascriptarraystestingautomated-teststestcafe

解决方案


请看以下示例,该示例演示了如何使用 TestCafe 检查表状态:

import { Selector, ClientFunction } from 'testcafe';

fixture `fixture`
    .page `https://jsfiddle.net/gv69jqrx/1/`;

test('Obtain array', async t => {
    await t
        .switchToIframe(Selector('#editor').find('[name="result"]'));

    const getCountries = ClientFunction(() => {
        const countries  = [];
        const columnKeys = ['country', 'capital', 'population', 'language'];
        const rows       = document.getElementsByTagName('tr');

        for (let i = 0; i < rows.length; i++) {
            const cells   = rows[i].getElementsByTagName('td');
            const country = {};

            if (!cells.length) continue;

            for (let j = 0; j < cells.length; j++)
                country[columnKeys[j]] = cells[j].textContent;

            countries.push(country);
        }

        return countries;
    });

    await t
        .expect(getCountries()).eql([
            { 
                country:    'USA',
                capital:    'Washington, D.C.',
                population: '309 million',
                language:   'English'
            },
            { 
                country:    'Sweden',
                capital:    'Stockholm',
                population: '9 million',
                language:   'Swedish'
            }
         ]);
});

如果您的情况不同,请更详细地描述它。测试代码和测试页面示例将非常有帮助。


推荐阅读